鱼C论坛

 找回密码
 立即注册
查看: 1180|回复: 0

[技术交流] Python 查看对象属性相关方法

[复制链接]
发表于 2020-3-15 22:00:32 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
Python 查看对象属性相关方法


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

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-22 13:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表