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

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值