python var()你可能没有彻底理解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Arctic_Beacon/article/details/84837773

先看官方文档

vars([object])

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__attribute.

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use atypes.MappingProxyType to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

from datetime import datetime

class person(object):
    "Person Class"
    def __init__(self,name,age,parent=None):
        self.name=name
        self.age=age
        self.created=datetime.today()
        self.parent=parent
        self.children=[]
        print('Created',self.name,'age',self.age)

    def setName(self,name):
        self.name=name
        print('Updated name',self.name)

    def setAge(self,age):
        self.age=age
        print('Updated age',self.age)
        
    def addChild(self,name,age):
        child=person(name,age,parent=self)
        self.children.append(child)
        print(self.name,'added child',child.name)
        
    def listChildren(self):
        if len(self.children)>0:
               print(self.name,'has children:')
               for c in self.children:
                    print(' ',c.name)
        else:
            print(self.name,'has no children')

    def getChildren(self):
        return self.children

上述文件存为people.py

from people import person

joe=person('Joe Bloggs',47)
joe.addChild('Dora',9)
joe.addChild('Dick',7)
joekids=joe.getChildren()

print(vars(joe))

for j in joekids:
    print(j.name,'attributes')
    print(vars(j))

输出:

Created Joe Bloggs age 47
Created Dora age 9
Joe Bloggs added child Dora
Created Dick age 7
Joe Bloggs added child Dick
{'name': 'Joe Bloggs', 'age': 47, 'created': datetime.datetime(2018, 12, 5, 16, 3, 41, 716207), 'parent': None, 'children': [<people.person object at 0x00000000033332E8>, <people.person object at 0x00000000032CFE10>]}
Dora attributes
{'name': 'Dora', 'age': 9, 'created': datetime.datetime(2018, 12, 5, 16, 3, 41, 760708), 'parent': <people.person object at 0x00000000032DB048>, 'children': []}
Dick attributes
{'name': 'Dick', 'age': 7, 'created': datetime.datetime(2018, 12, 5, 16, 3, 41, 818209), 'parent': <people.person object at 0x00000000032DB048>, 'children': []}

猜你喜欢

转载自blog.csdn.net/Arctic_Beacon/article/details/84837773
今日推荐