在类函数中定义类函数:Python

Iro*_*ard 2 python nested class

我有一个代码,我想在类函数中定义一个类函数.这是我想要做的更简单的例子.该计划的目标是打印4.

>>> class bluh:
...     def haha(self):
...             print 3
...     def __init__(self):
...             def haha(self):
...                     print 4
... 
>>> x = bluh()
>>> x.haha()
3
Run Code Online (Sandbox Code Playgroud)

我该怎么写这个程序来做我想要的呢?

mgi*_*son 6

这实际上取决于你想做什么.

>>> 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
Run Code Online (Sandbox Code Playgroud)

在前面的例子中,haha实际上并不是一个方法 - 它只是一个函数.但它会self从关闭和很多时候获得一个参考,这可能已经足够了.如果你真的想在一个实例上使用monkeypatch/duck punch一个新方法,你需要使用types.MethodType.请看这里的例子.