3

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?

IronBeard
  • 229
  • 2
  • 4
  • 12
  • 3
    If your goal is to print 4, why are you doing this instead of just defining `haha` as a regular method? What are you hoping to gain by doing it this way? – BrenBarn Feb 17 '13 at 19:17
  • 2
    My goal isn't *actually* to print 4. This is just much simpler version of what I'm trying to do, which involves control statements, lots of other methods, etc. I almost put a part explaining this at the end of my post, but eventually decided that most people who frequented this site could figure that out. – IronBeard Feb 17 '13 at 20:55
  • 1
    The point is, you haven't explained why you feel it's necessary to use nested functions in the first place. – BrenBarn Feb 17 '13 at 20:56

2 Answers2

9

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.

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

This will add a method to a class from an instance. In most cases not the thing you want to do, but the language makes it just that simple.

class A(object):
    def __init__(self):
        def foo(self):
            print "bar"
        self.__class__.foo = foo 

The use of such a trick can be justified when you build some kind of data-driven self-modifying code (not a every day case for most of us)

mderk
  • 796
  • 4
  • 13
  • 1
    Every time anyone does anything like that, Guido kills a kitten, thus have I heard. – bereal Feb 17 '13 at 19:21
  • It depends what you're going to accomplish. One shouldn't do this on a regular basis, but I can see some good use for such a technique. – mderk Feb 17 '13 at 19:30