1 class Student(): 2 name = 'lemon' 3 4 print(Student.__dict__) 5 print(Student.name) 6 Student.name = 'lemon-Xu' 7 print(Student.name)
- Class.__dict__:返回类相关信息
- Class.name:设置或返回属性
1 class Student(): 2 name = 'lemon' 3 4 def say(self,name): 5 self.name = name 6 print(self.name) 7 8 9 a = Student() 10 11 a.say('lemon-Xu') 12 13 Student.say(Student,'lemon-X')
- 类函数第一个参数必须传入一个对象
- 当实例化对象调用时传入自身.如果类对象调用时必须手动传入类对象
1 class Student(): 2 name = 'lemon' 3 4 def __init__(self,name): 5 self.name = name 6 7 8 a = Student('lemon-Xu') 9 b = Student('lemon-a') 10 11 print(a.__dict__) 12 print(b.__dict__) 13 print(Student.__dict__)
- __init__(self),建议只写一个,重载请参考:https://www.cnblogs.com/erbaodabao0611/p/7490439.html
1 class Student(): 2 __name = 'lemon' 3 4 def __init__(self,name): 5 self.__name = name 6 a = Student('lemon-X') 7 try: 8 print(a.name) 9 except : 10 print('双下滑线的变量名被更名,所以找不到它,它被改名为_Class__attribute') 11 print(a._Student__name) 12 13 print(Student._Student__name)
- 被__(双下划线)修饰的属性,会被更名为_Class__attribute
- 被_(单下划线)修饰的属性,是被保护的属性
1 class Pepole: 2 name = 'lemon' # 公共 3 __age = 18 # 私有 4 _adr = '百草路' # 受保护 5 6 def __init__(self,name): 7 self.name = name 8 9 def sleep(self): 10 print('困了睡觉....') 11 12 class Student(Pepole): 13 def work(self): 14 print("写作业") 15 16 def sleep(self): 17 self.work() 18 super().sleep() 19 20 s = Student('lemon') 21 print(Pepole.__dict__) 22 print(Student.__dict__) 23 print(s.__dict__) 24 s.sleep()
- super()方法得到父类
1 # extends super 2 3 class A(): 4 def __init__(self,name): 5 print('A') 6 print(name) 7 # 第一种 8 class B(A): 9 name = 'B' 10 def __init__(self,name): 11 A.__init__(self,name) 12 print('B') 13 14 def a(self): 15 print('当前类是:',self.name) 16 # 第二种 17 class C(B): 18 name = 'C' 19 def __init__(self,name): 20 super().__init__(name) 21 print('C') 22 23 def C2(self): 24 super().a() 25 26 a = A('lemon') 27 print() 28 c = C('lemon') 29 c.C2() 30 31 32 run: 33 A 34 lemon 35 36 A 37 lemon 38 B 39 C 40 当前类是: B
- super().方法,默认传入当前对象