jakuta
jakuta

Reputation: 130

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 }

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.

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

I expected that the results instance.__dict__ would contain a mapping for all the methods and attributes as key, value pairs.

Upvotes: 3

Views: 1998

Answers (1)

MaximGi
MaximGi

Reputation: 594

The methods are methods of the class, and not of the instance.

When calling instance.some_func(), you are actually calling A.some_func(instance).

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

This attribute of the class is then nowhere to be found in instance.__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}

Upvotes: 8

Related Questions