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

本文通过创建Person类并实例化,演示了如何利用Python内置函数vars()获取对象的属性字典,包括模块、类、实例等,并展示了如何更新和读取这些属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看官方文档

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': []}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞行codes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值