Sujet : Re: Difference method vs attribut = function
De : list1 (at) *nospam* tompassin.net (Thomas Passin)
Groupes : comp.lang.pythonDate : 29. Jun 2024, 22:01:49
Autres entêtes
Message-ID : <mailman.182.1719699957.2909.python-list@python.org>
References : 1 2
User-Agent : Mozilla Thunderbird
On 6/28/2024 12:08 PM, Ulrich Goebel via Python-list wrote:
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 that is the only difference?
class MyClass:
def __init__(self):
functionAttribute = None
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
By the way: in my usecase I want to pass different functions to different instances of MyClass. It is in the context of a database app where I build Getters for database data and pass one Getter per instance.
Thanks for hints
Ulrich
https://docs.python.org/3/library/functions.html#dir -
object.__dict__¶
A dictionary or other mapping object used to store an object’s (writable) attributes.
dir(object)
...
With an argument, attempt to return a list of valid attributes for that object.
"functionAttribute" is a class method, not an instance method. If you want an instance method:
class MyClass:
def __init__(self):
functionAttribute = None
self.instance_functionAttribute = None
def method(self):
print("I'm a method")