scu*_*bbo 6 python metaprogramming
我有Python背景(虽然完全是自学成才,所以我可能有一些不良习惯或误解),而我正在努力学习Ruby以扩大我的范围.
我正在阅读一些比较,并看到许多断言"Python不能进行元编程"(或者,更少的是,"Python不能像Meta一样简单地进行元编程").所以我离开后迅速阅读了关于元编程的内容,并且给人的印象是,它基本上是在运行时编辑类/对象的方法/行为(如果我不正确,请纠正我!).
我的印象是,由于Python是动态的,这应该不是问题.但是,我运行了以下测试代码,它没有给出我预期的响应:
>>> class foo:
... def make_hello_method(self):
... def hello(obj):
... print 'hello'
... self.hello = hello
...
>>> f = foo()
>>> f.hello()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: foo instance has no attribute 'hello'
>>> f.make_hello_method()
>>> f.hello()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: hello() takes exactly 1 argument (0 given)
Run Code Online (Sandbox Code Playgroud)
我的印象是,对象的每个方法都自动将对象本身作为第一个参数传递(因此将对象方法定义为常量要求(self, [...])).怎么f没有被传递给hello()?
你需要把它变成一个实例方法.在types模块中有一个类可以做到这一点.这将有效:
self.hello = types.MethodType(hello, self)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
339 次 |
| 最近记录: |