classmethod:类方法,把一个方法变成一个类中的方法,这个方法就直接可以被类调用,不需要依托任何对象什么时候用:当这个方法的操作只涉及静态属性的时候,就应该使用classmethod来装饰这个方法
class Fruit_store:
__discount = 0.5
def __init__(self,name,price):
self.name = name
self.__price = price
@property
def price(self):
return self.__price*self.__discount
# def change_discount(self,new_discount):
# self.__discount = new_discount
@classmethod #定义类方法,self变成cls
def change_discount(cls,new_discount):
cls.__discount = new_discount
apple = Fruit_store('apple',12.8)
print(apple.price)
# Fruit_store.change_discount(apple,0.8)
# apple.change_discount(0.8)#如果不定义类方法,需要用对象调用
Fruit_store.change_discount(0.8)
apple.change_discount(0.8)#静态方法同样可以被对象调用,但不推荐
print(apple.price)
staticmethod:静态方法,没有默认参数 在完全面向对象的程序中,如果一个函数既和对象没有关系 也和类没有关系 那么就用staticmethod将这个函数变成一个静态方法
class Longin:
def __init__(self,usr,pwd):
self.usr = usr
self.pwd = pwd
def login(self):pass
@staticmethod
def func():
usr = input('请输入姓名')
pwd = input('请输入密码')
return Longin(usr,pwd)
aike = Longin.func()
print(aike.pwd)
注意:类方法操作涉及静态属性的时候,他的操作对当前类的作用域有效,会影响所有调用该静态属性的方法。使用时需要注意self应该变为cls。
isinstance、issubclass
# isinstance(obj,cls)检查是否obj是否是类 cls 的对象
# issubclass(sub, super)检查sub类是否是 super 类的派生类
class A:
pass
class B:
pass
class C(A):
pass
a = A()
print(isinstance(a,A))
print(isinstance(a,B))
print(issubclass(C,A))
#打印:
True
False
True
来源:https://www.cnblogs.com/aizhinong/p/11475697.html