再次学习类_1
类的单继承,重写构造函数
class BaseClass: def __init__(self, name, age): self.name = name self.age = age def get_name(self): print('this is BaseClass Fun') return self.name def set_age(self, age): self.age = age class ClassNoInit(BaseClass): #init在子类中可以不定义 def get_age(self): return self.age class ClassNewInit(BaseClass): #重写父类init使用下面方法 def __init__(self, sex, name, age): super().__init__(name, age) self.sex = sex def get_sex(self): return self.sex def get_name_new(self): #指定基类方法调用 return BaseClass.get_name(self) if __name__ == '__main__': subInstance1 = ClassNoInit('flagzhang', 36) print(subInstance1.get_name()) subInstance2 = ClassNewInit('man', 'flag', 37) print(subInstance2.get_name()) print(subInstance2.get_sex()) print(subInstance2.get_name_new())
类的多继承
class BaseClass: def __init__(self, name, age): self.name = name self.age = age def get_name(self): print('this is BaseClass Fun') return self.name def set_age(self, age): self.age = age class BaseClass1: def __init__(self, work, sal): self.work = work self.sal = sal def get_work(self): return self.work class MutileBaseClass(BaseClass, BaseClass1): #多继承默认super.__init__()只继承第一个父类的构造函数, def __init__(self, name, age, work, sal): BaseClass.__init__(self, name, age) BaseClass1.__init__(self, work, sal) if __name__ == '__main__': mutileBaseInstance1 = MutileBaseClass('flag', 36, 'engineer', 28000) print(mutileBaseInstance1.get_work())
dataclass
from dataclasses import dataclass @dataclass class Person: name: str age: int work: str if __name__ == '__main__': person1 = Person('flag_dataclass', 36, 'engineer') print(person1.name)
类的私有变量
class PrivateAttr: #双下划线的属性或者方法在字节编码时会给该对象前面加上一个下划线"_类名"的前缀,所以实例无法访问,可以通过加上"_类名"显式访问 def __init__(self, name, age): self.name = name self.__age = age def get_age(self): return self.__age def __get_name(self): return self.name if __name__ == '__main__': private1 = PrivateAttr('flagzhang_pri', 36) print(private1._PrivateAttr__age) print(private1.get_age()) print(private1.get_age()) print(private1._PrivateAttr__get_name())