python学习7-类里面的__dict__属性

前言

python是面向对象的,对象有属性和方法,可以通过__dict__查看对象的属性

__dict__查看对象属性

首先弄清楚2个概念,类(A)和类的实例对象(A()),如下代码

  • count 是类A的属性
  • name、age 是A类的实例对象A()的属性
  • begin 是实例方法,默认带self参数
  • mid是静态方法,可以不带默认参数
  • end是类的方法,默认带cls参数
class A:
count=0
def __init__(self):
self.name="hui"
self.age=18
def begin(self):
self.score="70"
print("开始了")
@staticmethod
def mid():
print("中间")
@classmethod
def end(cls):
cls.height="180"
print("结束")

a=A()
print(A.count)
print(a.name)
a.begin()
A.mid()
A.end()
print(A.__dict__) #A类属性
print(a.__dict__) #A类的实例对象属性

A类有属性和方法,抽象的来讲,方法也可以看成类的属性(方法属性) 

运行结果

0
hui
开始了
中间
结束
{'__module__': '__main__', 'count': 0, '__init__': <function A.__init__ at 0x0000000002565158>, 'begin': <function A.begin at 0x00000000025652F0>, 'mid': <staticmethod object at 0x0000000002577390>, 'end': <classmethod object at 0x00000000025773C8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None, 'height': '180'}
{'name': 'hui', 'age': 18, 'score': '70'}

 从运行结果可以看出,A的类属性有count,height,还有定义的一些方法(__init__构造方法,还有实例方法,静态方法,类方法);

A()实例对象有__init__构造方法的name、age,实例方法的score;  

如果我们直接A.name和A.score就会报错

print(A.name) #报错:AttributeError: type object 'A' has no attribute 'name'
print(A.socre) #报错
print(A.count) #0

 因为name和age属性在__init__构造方法里面,只有当A类实例化的时候,才会执行__init__构造方法,这时候才会有name和age属性;

scroe只有通过实例化对象调用;  

 继承时__dict__属性

当B类继承A类的时候,A类和B类都有自己的类属性count,也各自有自己的__init__构造方法

class A:
    count=0
    def __init__(self):
        self.__name="hui"
        self.age=18
    def begin(self):
        print("开始了")
    @staticmethod
    def mid():
        print("我是静态方法")
    @classmethod
    def end(cls):
        print("我是类方法")

class E(A):
    count=30
    def __init__(self):
        super().__init__()
        self.__name="xiha"
        self.age=50
    def new(self):
        print("我是E类的")
print(A.__dict__) #count,__init__,begin,mid,end
print(E.__dict__) #count,__init__,new
a=A()
e=E()
print(a.__dict__) #name,age=18
print(e.__dict__) #name,age=50

 运行结果

{'__module__': '__main__', 'count': 0, '__init__': <function A.__init__ at 0x0000000002555158>, 'begin': <function A.begin at 0x00000000025552F0>, 'mid': <staticmethod object at 0x0000000002567278>, 'end': <classmethod object at 0x00000000025672E8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
{'__module__': '__main__', 'count': 30, '__init__': <function E.__init__ at 0x0000000002555488>, 'new': <function E.new at 0x0000000002555598>, '__doc__': None}
{'_A__name': 'hui', 'age': 18}
{'_A__name': 'hui', 'age': 50, '_E__name': 'xiha'}

 从运行结果可以看出

A类和B类的类属性count是不一样的

虽然B类继承了A类,方法属性也不一样,可以清楚的区分出那些是A类的方法属性,那些是B类的方法属性; 

 

越努力,越幸运!!! good good study,day day up!!!
原文地址:https://www.cnblogs.com/canglongdao/p/15162970.html