Did you know, that you can also define methods in Python this way?

def pr(*args):
print("i got %r" % args)

class Foo:
bar = pr

>>> Foo().bar()
i got <__main__.Foo object at 0x7f6b8b4ed950>

@Wolf480pl I used to monkey-patch classes this way.

def thing_that_wasnt_there(self):
# do something with the class

Class.new_thing = thing_that_wasnt_there


Yesterday I was modifying a Django app, had a code like this:

class SomeClass:
form_class = OtherClass

and needed to intercept the instantiation of OtherClass by whoever reads form_class, and modify the arguments passed to constructor.

So I tried

def wrapper(**kwargs):
return OtherClass(..., **kwargs)

class SomeClass:
form_class = wrapper

and suddenly I started getting self.

So then I did:

class SomeClass:
def form_class(self, **kwargs):
return OtherClass(..., **kwargs)

Sign in to participate in the conversation

Welcome to your niu world ! We are a cute and loving international community O(≧▽≦)O !