On 4 Mar, 09:22, "甜瓜" <[EMAIL PROTECTED]> wrote: > > This is a big problem puzzles me for a long time. The core question is: > How to dynamically create methods on a class or an instance? > > Let me state it step by step. > 1. > def gunc(self): > pass > class A(object): > def func(self): > pass > a = A() > a.func # gives "bound method", type is "instancemethod" > A.func # gives "unbound method", type is "instancemethod" > gunc # gives "function", type if "function" > > # ?? Does this line attach a method to instance? ... I don't think so. > a.gunc = gunc
No, unfortunately not. You might get the detailed explanation from someone else, but generally, you have to assign functions to classes; these are then exposed as methods via instances of such classes. A.gunc = gunc > I found stardard library 'new' may help. Is that right? Yes, it can help: import new a.gunc = new.instancemethod(gunc, a, A) > 2. > a = A() # instance of old class A > # Do attach a new method to class A... > b = A() # instance of new class A > Does "a" can get the new method automatically? Can "a" get the new method automatically? Apparently, yes: class A: pass a = A() def f(self, x): print x A.f = f a.f(123) # works, printing 123 > Does new method have the *same* concept level with old methods? > Especially, if there > are classes inherit from class A, how does name resolution work on this case? As far as I'm aware, after you've added a method to a class, instances will regard the method like all the previously existing methods, since method lookup is a dynamic operation. I'll not address your other questions in this message since I'm not a heavy user of decorators and don't want to provide a quick answer without fully testing it first. However, it is important to remember that the "magic" occurs for class attributes, not instance attributes. So, for example, it's quite possible that you'd want to assign a function to an instance attribute, but you wouldn't want the instance to suddenly "own" that function... def somefunc(x, y): # Do something with x and y... return x + y a = A() a.somefunc = somefunc # store the function somewhere # Later... adder = a.somefunc # Later still... result = adder(p, q) # wouldn't work if somefunc became a method Python seems to do the most intuitive thing, I think, but it's quite tricky to contemplate all the implications. Paul P.S. I can never really remember all the different situations and outcomes with method assignment, but then it's something I hardly ever do. I'd be interested to know whether my situation is unusual, however.
-- http://mail.python.org/mailman/listinfo/python-list