2 ms·
You only have to list self in the declaration, you don't have to pass the instance to itself. Borrowing masklinn's example: >>> class Foo(object): ... d
by majormajor 14y ago
You only have to list self in the declaration, you don't have to pass the instance to itself.
Borrowing masklinn's example:
>>> class Foo(object):
... def __init__(self):
... self.n = 42
... def bar(self):
... return self.n
...
>>> f = Foo()
>>> f.bar()
42
- masklinn 14y agoAlthough you can also (and that can be rather neat when e.g. mapping or filtering) use the method as a function, if you get it from the class: f = Foo() Foo.bar(f) note that it will typecheck the first argument to ensure it's an instance of `Foo`, it's not a function, it's an unbound method: >>> class Bar(object): pass ... >>> b = Bar() >>> b.n = 66 >>> Foo.bar(b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method bar() must be called with Foo instance as first argument (got Bar instance instead)
- mattdeboard 14y agoIf you want to do that use the @staticmethod decorator.
- masklinn 14y agoOh just, you know, create a function... There's nothing more pointless than @staticmethod, unless it was used specifically to port code it should mark whoever used it for a whipping.