Message261892
| Author |
Rosuav |
| Recipients |
Rosuav, docs@python, georg.brandl |
| Date |
2016年03月17日.07:16:36 |
| SpamBayes Score |
-1.0 |
| Marked as misclassified |
Yes |
| Message-id |
<1458198996.25.0.438002592338.issue26576@psf.upfronthosting.co.za> |
| In-reply-to |
| Content |
The remaining difference that's actually of use, perhaps. But the decoration itself happens before the name is bound. It's impossible to describe in Python code; but it can be probed - you can monkeypatch a class using a decorator:
def monkeypatch(cls):
orig = globals()[cls.__name__] # Undocumented magic
print("Monkeypatch",id(cls),"into",id(orig))
for attr in dir(cls):
if not attr.startswith("_"):
setattr(orig,attr,getattr(cls,attr))
return orig
class Foo:
def method1(self):
print("I am method 1")
print("Foo is currently",id(Foo))
some_object = Foo()
@monkeypatch
class Foo:
def method2(self):
print("I am method 2")
print("Foo is now",id(Foo))
some_object.method1()
some_object.method2()
Is this undocumented behaviour? Should it be supported? It works on every Python I've tried it on (CPython 2.7 and 3.6, PyPy2 and PyPy3, Jython, and MicroPython), but it's not something I'd depend on in production code unless it's documented. |
|
History
|
|---|
| Date |
User |
Action |
Args |
| 2016年03月17日 07:16:36 | Rosuav | set | recipients:
+ Rosuav, georg.brandl, docs@python |
| 2016年03月17日 07:16:36 | Rosuav | set | messageid: <1458198996.25.0.438002592338.issue26576@psf.upfronthosting.co.za> |
| 2016年03月17日 07:16:36 | Rosuav | link | issue26576 messages |
| 2016年03月17日 07:16:36 | Rosuav | create |
|