python 查看对象属性相关方法(__dict__, dir(), vars(), locals())

本文深入探讨了Python编程的核心概念,包括内置类型对象、dir()方法、vars()和locals()函数的使用,以及如何理解对象的__dict__属性。通过实例演示了如何操作类和实例属性,展示了Python在面向对象编程中的强大功能。

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

---恢复内容开始---

1. 对象 __dict__

object.__dict__一般是字典或其他映射对象,用来存储一个对象(可写的)的属性。

    A dictionary or other mapping object used to store an object’s (writable) attributes.

内建类型对象中是不存在这个属性的。内建对象访问会出现AttributeError错误。

>>> lst = [1, 2]
>>> lst.__dict__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute '__dict__'

类对象Class.__dict__只返回当前类的属性字典,但不包含其基类的属性。dir(Class)会返回当前类以及它的所有基类的类属性名,即当前类及所有基类的__dict__键值。
实例对象obj.__dict__返回实例对象绑定的属性字典。dir(obj)会返回实例属性和构造类以及所有基类的属性列表。

class ClassA:

    num_A = 1

    def foo_A(self):
        pass

    def __str__(self):
        return 'this is ClassA'


class ClassB(ClassA):

    num_B = 2

    def __init__(self, name='ClassB'):
        self.name = name

    def foo_B(self):
        pass

print(ClassB.__dict__)  # 类对象的__dict__不包含基类的属性
# {'__module__': '__main__', 'num_B': 2, '__doc__': None, 'foo_B': # <function ClassB.foo_B at 0x7f1a78dadbf8>, '__init__': <function ClassB.__init__ at 0x7f1a78dadb70>} print(dir(ClassB)) # 会返回当前类以及它的所有基类的`__dict__`键值列表 # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', # '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', # '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', # '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', # '__str__', '__subclasshook__', '__weakref__', 'foo_A', 'foo_B', 'num_A', 'num_B'] objB = ClassB() print(objB.__dict__) # {'name': 'ClassB'} objB.grade = 123 # 运行时增加实例属性 print(objB.__dict__) # {'grade': 123, 'name': 'ClassB'} print(dir(objB)) # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', # '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', # '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', # '__subclasshook__', '__weakref__', 'foo_A', 'foo_B', 'name', 'num_A', 'num_B'] lst = dir(objB) lst.remove('name') lst.remove('grade') print(lst == dir(ClassB)) # dir(obj)除去obj绑定的属性和dir(class)得到内容的一样 # True

 

2. dir() 方法

dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. 不带参数时,返回当前范围内名称列表; 带参数时,返回对象有效属性的列表。 If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes. 如果参数对象有方法__dir__(),该方法将被调用。 If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__(). 如果对象没有__dir__()方法 The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information: If the object is a module object, the list contains the names of the module’s attributes. 作用于模块 If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. 作用于类对象 Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes. 作用与实例对象

1) dir()不带参数时,返回当前范围内名称列表。和locals(),vars()不带参数类似,后面返回的是 {名称列表,值} 的字典。
2) dir(module) 作用于模块时,返回模块的属性列表。即模块struct.__dict__的键值列表。

import struct

print(dir())   # show the names in the module namespace
# ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', # '__name__', '__package__', '__spec__', 'struct'] print(set(locals().keys()) == set(dir())) # True print(dir(struct)) # show the names in the struct module # ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', # '__package__', '__spec__', '_clearcache', 'calcsize', 'error', 'iter_unpack', 'pack', 'pack_into', # 'unpack', 'unpack_from'] print(set(dir(struct)) == set(struct.__dict__.keys())) # True

3) 当dir(obj)作用与实例对象,且它的构造类或基类有__dir__方法,dir(obj)返回自定义的列表内容。

class ClassA:

    num_A = 1

    def foo_A(self): pass def __str__(self): return 'this is ClassA' def __dir__(self): return ['height', 'color', '222'] class ClassB(ClassA): num_B = 2 def __init__(self, name='ClassB'): self.name = name def foo_B(self): pass objB = ClassB() objB.grade = 123 print(dir(objB)) # ['222', 'color', 'height']

4)当dir(obj)作用于实例对象,且它的构造类或基类没有__dir__方法,则dir(obj)返回obj的实例属性,还有构造类及基类的类属性。

5)当dir(class作用于类对象,返回当前类及所有基类的类属性列表。

class ClassA:

    num_A = 1

    def foo_A(self):
        pass

    def __str__(self):
        return 'this is ClassA'

    # def __dir__(self):
    #     return ['height', 'color', '222']

class ClassB(ClassA):

    num_B = 2

    def __init__(self, name='ClassB'):
        self.name = name

    def foo_B(self):
        pass
        
print(dir(ClassB))
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', # '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', # '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', # '__reduce__', '__reduce_ex__', '__repr__','__setattr__', '__sizeof__', # '__str__', '__subclasshook__', '__weakref__', 'foo_A', 'foo_B', 'num_A', 'num_B'] objB = ClassB() objB.grade = 123 print(dir(objB)) # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', # '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', # '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', # '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', # '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'foo_A', # 'foo_B', 'grade', 'name', 'num_A', 'num_B']

 

3. vars() 和 locals()

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 a types.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.

vars([object])就是返回对象__dict__的内容,无论是类对象还是实例对象,vars([object]) == object.__dict__。当然,参数对象需要有一个__dict__属性。同样的,内建对象没有__dict__属性会报TypeError错误。

>>> lst = [1, 2]
>>> vars(lst)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module> TypeError: vars() argument must have __dict__ attribute
class ClassA:

    num_A = 1

    def foo_A(self): pass def __str__(self): return 'this is ClassA' # def __dir__(self): # return ['height', 'color', '222'] class ClassB(ClassA): num_B = 2 def __init__(self, name='ClassB'): self.name = name def foo_B(self): pass objB = ClassB() objB.grade = 123 print(vars(ClassB) == ClassB.__dict__) # True print(vars(objB) == objB.__dict__) # True

locals()返回调用者当前局部名称空间的字典。在一个函数内部,局部名称空间代表在函数执行时候定义的所有名字,locals()函数返回的就是包含这些名字的字典。

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
print(locals())
# {'__name__': '__main__', '__file__': '/home/eliefly/PycharmProjects/test_folder/test.py', # '__spec__': None, '__cached__': None, '__doc__': None, # '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fadedf59518>, # '__builtins__': <module 'builtins' (built-in)>, '__package__': None} print(vars() == locals()) # True

---恢复内容结束---

转载于:https://www.cnblogs.com/tyxr/p/9590108.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值