Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #196347
| From | "Peter J. Holzer" <hjp-python@hjp.at> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Difference method vs attribut = function |
| Date | 2024-06-29 21:53 +0200 |
| Message-ID | <mailman.180.1719690794.2909.python-list@python.org> (permalink) |
| References | <20240628180854.7ee713db744e9672ad668f36@fam-goebel.de> <20240629195305.kxzys5ht7hottfup@hjp.at> |
[Multipart message — attachments visible in raw view] - view raw
On 2024-06-28 18:08:54 +0200, Ulrich Goebel via Python-list wrote:
> 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,
The other way around: It includes only the attributes, not the methods.
> 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")
Here is the other main difference: The object is not passed implicitely
to the function. You have no way to access mc here.
You can create a method on the fly with types.MethodType:
import types
mc.functionAttribute = types.MethodType(function, mc)
> 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.
Or in this case, since each function is specific to one instance, you
could just use a closure to capture the object. But that might be
confusing to any future maintainers (e.g. yourself in 6 months), if the
method doesn't actually behave like a method.
hp
--
_ | Peter J. Holzer | Story must make more sense than reality.
|_|_) | |
| | | hjp@hjp.at | -- Charles Stross, "Creative writing
__/ | http://www.hjp.at/ | challenge!"
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Difference method vs attribut = function "Peter J. Holzer" <hjp-python@hjp.at> - 2024-06-29 21:53 +0200
csiph-web