I have a code in which I want to defina a class function inside a class function. Here’s a simpler example of what I want to do. The goal of this program is to print 4.
>>> class bluh:
... def haha(self):
... print 3
... def __init__(self):
... def haha(self):
... print 4
...
>>> x = bluh()
>>> x.haha()
3
How should I actually write this program to do what I want?
This really depends on what you want to do.
In the previous example,
hahaisn’t actually a method — It’s just a function. But it will pick up a reference toselffrom the closure and a lot of the time, that’s probably good enough. If you actually want to monkeypatch/duck punch a new method on an instance, you’ll need to usetypes.MethodType. See here for an example.