属性的初识:将一个方法伪装成一个属性,在代码的级别上没有本质的提升,但是让其看起来很合理
class Person: def __init__(self,name,age): self.name = name if type(age) is int: self.__age = age else: print( '你输入的年龄的类型有误,请输入数字') @property def age(self): return self.__age @age.setter def age(self,a1): '''判断,你修改的年龄必须是数字''' if type(a1) is int: self.__age = a1 else: print('你输入的年龄的类型有误,请输入数字') @age.deleter def age(self): del self.__age p1 = Person('帅哥',20) print(p1.age) print(p1.__dict__) p1.age = 23 print(p1.age) del p1.age
类方法与静态方法
类方法,通过类名调用的方法,类方法中第一个参数约定的俗称cls,Python自动将类名传给cls
类方法的应用场景:
1.类中方法不需要对象参与
2.对类中的静态变量进行改变
3.继承中,父类得到子类的类空间