Python Forum

Full Version: Difference between method and attribute holding a function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
a class can have methods, and it can have attributes, which can hold a function. Both is well known, of course.
My question: Is there any difference?
The code snipped shows that both do what they should do. But __dict__ includes just the method, while dir detects the method and the attribute holding a function. My be this is the only difference?

class MyClass:

    def __init__(self):
        self.functionAttribute = lambda x: ''
        
    def method(self):
        print("I'm a method")

def function():
    print("I'm a function passed to an attribute")

mc = MyClass()
mc.functionAttribute = function

mc.method()
mc.functionAttribute()

print('Dict: ', mc.__dict__)    # shows functionAttribute but not method
print('Dir:  ', dir(mc))        # shows both functionAttribute and method
Background to my question: In a context of a database app I want to pass different functions to different instances of MyClass. I'm building Getters for database data and pass one Getter per instance.

Thanks for hints
Ulrich
Quote:But __dict__ includes just the method,
MyClass.__dict__ includes method(), but mc.__dict__ does not. method() is an attribute of the class, and only appears in the class's __dict__. mc is an instance of MyClass, and method is not an attribute of the instance. method() does not appear in mc.__dict__.

"def method(self):" is problem code. It should not be an instance method (should not have self as the first argument). self is not used, and having self prevents using the function unless you first make an instance of MyClass.

MyClass should be written this way.
class MyClass:
 
    def __init__(self):
        self.functionAttribute = lambda x: ''

    @staticmethod
    def method(text):
        print(text)

x = MyClass()
x.method("Called using an instance.")

MyClass.method("Called as a function in the MyClass namespace.")
Output:
Called using an instance. Called as a function in the MyClass namespace.
(Jun-29-2024, 07:57 PM)ulrich Wrote: [ -> ]print('Dict: ', mc.__dict__) # shows functionAttribute but not method
Methods defined in the class body are part of the class attribute dictionary,not the instance dictionary.
# Instance dictionary
>>> mc.__dict__
{'functionAttribute': <function function at 0x000001B9B775EAC0>

# Class attribute dictionary,now see the <method>
>>> MyClass.__dict__
mappingproxy({'__dict__': <attribute '__dict__' of 'MyClass' objects>,
              '__doc__': None,
              '__init__': <function MyClass.__init__ at 0x000002413180EB60>,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
              'method': <function MyClass.method at 0x000002413180EC00>})