Python function pointer in class __init__ -
in code below, class has member function set point function defined outside class. in class b, same function set external pointer in class definition. calling function object of type fail, because self not passed function. b, self gets passed. why self passed b, not a?
def f1(s,a): print s print class a(object): def __init__(self): self.fp1 = f1 class b(object): fp1 = f1 a=a() b=b() try:a.fp1("blaa") except exception, e: print `e` try:b.fp1("bluu") except exception, e: print `e`
output:
typeerror('f1() takes 2 arguments (1 given)',) <__main__.b object @ 0x2ab0dacabed0> bluu
when did self.fp1 = f1
assigned function instance variable of class a
. when call have pass 2 arguments.
when did:
class b(object): fp1 = f1
during creation process of class b
python found function fp1
in class scope , created instancemethod
(replaced variable name fp1
instancemethod
created function held before). when call instancemethod
on object self
gets automatically passed first argument.
you can check typing:
>>> = a() >>> b = b() >>> type(a.fp1) function >>> type(b.fp1) instancemethod
Comments
Post a Comment