Python中面向对象的相关概念和继承
父类
class Human():
sum =0
def __init__(self, name, age, character="开朗"):# 父类构造函数
self.name = name
self.age = age
self.__character = character# 私有化,子类将不能继承
self.tell_sum()# 调用类内方法
def __character(self):# 私有化函数,实例化对象和子类均不能访问
print(self.__character)
def tell_name(self):#公共函数
print(self.name)
@classmethod # 装饰器,变成类方法
def tell_sum(cls):
cls.sum +=1
print("我是第"+str(cls.sum)+'个人')
@staticmethod # 装饰器,变成静态方法
def tell_species(sex='女'):
print("我是个"+sex+"人")
子类
from mine.parentimport Human
class Student(Human):
sum =0
def __init__(self, school, name, age):
self.school = school
super(Student, self).__init__(name, age)# 重载父类构造方法
def print_info(self):
print('我叫'+self.name +',' +'今年'+str(self.age)+','+'来自'+self.school)
student1 = Student('华侨大学', 'Byron', 18)# 实例化对象
print(student1.__dict__)# 查看对象有的属性
student1.tell_name()# 调用父类的共有函数
student1.print_info()# 调用类的方法
student1.tell_species('男')# 调用类的静态方法