Defining class functions inside class functions: Python

class, nested, python

Solution

This really depends on what you want to do.

>>> class Foo(object):
...     def haha(self):
...         print 3
...     def __init__(self):
...         def haha():
...             print 4
...         self.haha = haha
... 
>>> a = Foo()
>>> a.haha
<function haha at 0x7f4539e25aa0>
>>> a.haha()
4

In the previous example, `haha` isn't actually a method -- It's just a function. But it will pick up a reference to `self` from 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 use `types.MethodType`. See here for an example.

Problem

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?

Original source

Related problems