__dict__用法

文章展示了在Python中如何使用__dict__来查询和创建对象的属性。通过创建Person和Student类,以及它们的实例stu,说明了__dict__如何存储实例变量。同时,文章还提到了dir()函数用于列出对象的所有方法和属性,包括从父类继承的。
摘要由CSDN通过智能技术生成

__dict__只能查询自身的属性,但是也能创建属性,如下:

class Person:
    address = '海洋小区'
    def __init__(self, name):
        self.name = name


class Student(Person):
    def __init__(self, school_name):
        self.school_name = school_name


stu = Student('黑马')
print(stu.__dict__)
print(Student.__dict__)
print(Person.__dict__)
stu.__dict__['age'] = 18
print(stu.__dict__)

# dir函数可以查询一个对象中的所有方法,包含这个对象的父类
print(dir(stu))

结果

{'school_name': '黑马'}
{'__module__': '__main__', '__init__': <function Student.__init__ at 0x000002050370C9D8>, '__doc__': None}
{'__module__': '__main__', 'address': '海洋小区', '__init__': <function Person.__init__ at 0x00000204F0DF9840>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
{'school_name': '黑马', 'age': 18}
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'address', 'age', 'school_name']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值