python---类属性和实例属性

    技术2025-08-13  8

    type 与 isinstance

    在python中,type代表着类型,而isinstance则是为是否关系;二者在应用中都有很大的空间。 type 不考虑 继承关系 isinstance 考虑继承关系

    # class Father(object): # # def dele(self): # # raise NotImplementedError # # # # def crea(self): # # raise NotImplementedError # # # # class Son(Father): # # def dele(self): # # print("aaa") # # # # # r = Son() # # # r.crea() # # # r.dele() # 可以访问到父类的方法 # # # # ''' # # 1. 子类 如果不重写父类的方法 访问时 直接抛出异常 # # ''' # # r = Son() # # r.dele() # import abc # # 使用抽象基类的方法来定义父类 不是继承object 而是继承abc.ABCMeta # class Father(metaclass=abc.ABCMeta): # @abc.abstractmethod # 装饰器 变成抽象基类的方法 # def dele(self): # pass # # @abc.abstractmethod # def crea(self): # pass # # class Son(Father): # def dele(self): # print("aaa") # # # 加上装饰器 后 不重写才会报错 # r = Son() # r.crea() # a = 1 # b = 'happy' # # print(isinstance(a,(int,str))) # 返回值为布尔值, ()--> or # print(type(b)) # <class 'str'> class Father(object): pass class Son(Father): pass ls = Son() # print(isinstance(ls,Son)) # true # print(isinstance(ls,Father)) # true 继承关系 # # print(type(ls)) # <class '__main__.Son'> # print(type(ls) is Son) # 判断是否为同一地址 true # print(type(ls) is Father) # False 不考虑继承关系 两个类两个内存地址 print(f"Son_id:{id(Son)}, Father_id:{id(Father)}") # Son_id:2845519172888, Father_id:2845519160616

    类属性和实例属性

    对象是可以向上查找的,所以可以访问到类属性;当对象自己有该实例属性时,则可以访问到类属性。 代码运行从下到上,从左到右;对象可以向上查找,访问到类属性,但是类属性不能向下查找,只能访问类属性。 深度优先;广度优先;

    class Father(object): # 类属性 cls_ins = 1 def __init__(self,a,b): # 实例属性 self.a = a self.b = b h = Father(5,2) # print(h.cls_ins,h.b,h.a) Father.cls_ins = 765 # 覆盖 h.cls_ins = 521 # 封装 print(Father.cls_ins) print(h.cls_ins)

    利用mro查找顺序:

    class D(object): pass class B(D): pass class C(D): pass class A(B,C): pass print(A.__mro__) # A,B,C,D
    Processed: 0.010, SQL: 9