property函数
property是将类中的方法转化成属性的装饰器方法
1 class Goods: 2 __discount=0.8 3 def __init__(self,price): 4 self.__price=price 5 self.name='apple' 6 @property 7 def price(self): 8 return self.__price*Goods.__discount 9 @price.setter 10 def price(self,new): 11 self.__price=new 12 @price.deleter 13 def price(self): 14 del self.__price 15 apple=Goods(10) 16 print(apple.price) #8.0 17 print(apple.__dict__) #{'_Goods__price': 10, 'name': 'apple'} 18 apple.price=8 19 print(apple.price) #6.4 20 del apple.name 21 print(apple.__dict__) #{'_Goods__price': 8}
只有当被property装饰的方法又实现了一个同名方法,且被setter装饰器装饰了,且在对被装饰的方法赋值的时候就会触发被setter装饰的方法。
用来保护一个变量,在修改的时候可以添加一些保护条件。
一个方法被伪装成属性之后,可以执行一个属性的增删改查的操作
增加和修改就对应了被setter装饰的方法,这个方法有一个必传的参数,表示赋值的时候等号后面的值
删除一个属性对用了deleter装饰的方法,这个方法不能在执行的时候真的删除这个属性,而是在代码中执行什么就有什么效果。
classmethod函数
1 #如何修改折扣呢,也就是类中的静态属性 2 class Goods: 3 __discount=0.8 #静态属性 4 def __init__(self,price): #对象属性 5 self.__price=price 6 @property 7 def price(self): 8 return self.__price*Goods.__discount 9 @classmethod 10 def change_discount(cls,new): #类方法,通过类直接修改 11 cls.__discount=new 12 Goods.change_discount(0.7) 13 print(Goods.__dict__) #{'__module__': '__main__', '_Goods__discount': 0.7, '__init__': <function Goods.__init__ at 0x00000237FA25FA60>,........}
类方法的特点:
只使用类中的资源,且这个资源可以直接用类名引用的使用,那这个方法应该被改为一个类方法
staticmethod
不用传参,放在类中,当普通函数使用,经类直接调用
1 class Student: 2 @staticmethod 3 def login(user,www): 4 print('IN IN IN') 5 Student.login() #IN IN IN 6 Student.login('user','www') #IN IN IN
类
静态属性 类 所有的对象都统一拥有的属性
类方法 类 如果这个方法涉及到操作静态属性、类方法、静态方法 cls表示类
静态方法 类 普通方法,不使用类中的命名空间以及对象的命名空间,一个普通的函数 没有默认参数(staticmethod方法的)
方法 对象 self表示对象
property方法 对象 self表示对象
isinstance函数
1 class A: 2 pass 3 class B(A): 4 pass 5 a=A() 6 b=B() 7 print(type(a)is A) #True 8 print(type(b)is A) #False 9 print(isinstance(a,A)) #True 10 print(isinstance(b,A)) #True 11 print(isinstance(a,B)) #False
检测对象和类之间的关系
issubclass函数
1 class A: 2 pass 3 class B(A): 4 pass 5 print(issubclass(A,B)) #False 6 print(issubclass(B,A)) #True
检测类与类之间的关系,父类在后为true