Python对象实例中的dict不包含该类的方法 [英] dict in Python object instance doesn't contain the methods of the class
问题描述
创建对象的实例时,其字典不包含类方法。
When an instance of an object is created, its dict does not contain the classes methods. An example would be
class A(object):
def __init__(self, value):
self.value = value
def some_func(self): pass
instance = A('some_value')
print(instance.__dict__) #prints { 'value':'some_value }
为什么它也不包含方法。我知道打印 A .__ dict __
将打印包含该函数的mappingproxy,但是对于A的实例则不会发生。
Why doesn't it contain the methods also. I know that printing A.__dict__
will print a mappingproxy that contains the function, but this doesn't happen for the instance of A.
我尝试研究如何映射类的实例方法。如果使用dict完成此操作。我确实知道实例方法还具有字典和其他预定义的属性。
I have tried researching how the instance methods of a class are mapped. If this is done using dict. I do know that the instance method also has a dict and other predefined attributes.
class A(object)
def __init__(self, value):
self.value = value
def some_func(self): pass
instance = A('this')
instance.__dict__ # will print {'value':'some_value'}
A.__dict__ # will print a mapping proxy
我希望结果 instance .__ dict __
将包含所有方法和属性(作为键,值对)的映射。
I expected that the results instance.__dict__
would contain a mapping for all the methods and attributes as key, value pairs.
推荐答案
方法是方法
调用 instance.some_func()
时,实际上是在调用 A.some_func(instance)
When calling instance.some_func()
, you are actually calling A.some_func(instance)
为了说明,我向A添加了一个属性(classattr ='foo') :
To illustrate, I added an attribute to A (classattr = 'foo') :
class A:
classattr = 'foo'
def __init__(self, value):
self.value = value
def some_func(self):
return 1
instance = A('this')
print(f'instance dict : {instance.__dict__}') # will print {'value':'some_value'}
print(f'class dict : {A.__dict__}') # will print a mapping proxy
该类的属性不存在 dict ::
instance dict : {'value': 'this'}
class dict : {'__module__': '__main__', 'classattr': 'foo', '__init__': <function A.__init__ at 0x0000018AAB2A2400>, 'some_func': <function A.some_func at 0x0000018AAB2A2488>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
这篇关于Python对象实例中的dict不包含该类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!