Case Statements

Antoon Pardon antoon.pardon at rece.vub.ac.be
Thu Mar 17 04:38:09 EDT 2016


Op 17-03-16 om 00:14 schreef Chris Angelico:
> def monkeypatch(cls):
>     orig = globals()[cls.__name__]
>     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()

This seems close enough as far as I am concerned.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

def monkeypatch(cls, orig):
    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()

class Foo2:
    def method2(self):
        print("I am method 2")

monkeypatch(Foo2, Foo)

print("Foo is now",id(Foo))

some_object.method1()
some_object.method2()




More information about the Python-list mailing list