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?

3
  • 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? Commented Feb 17, 2013 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. Commented Feb 17, 2013 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. Commented Feb 17, 2013 at 20:56

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

2 Comments

Every time anyone does anything like that, Guido kills a kitten, thus have I heard.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.