About instance.name look up order

Prim ukim86 at gmail.com
Thu Dec 29 11:07:11 EST 2011


First, sorry about my poor english.
Put these in IPython under ubuntu.
-------------------------------------------------------------------------------------
class C:
    def __init__(self):
        self.x = 1
    def print(self):
        print self.x
c = C()
c.x --> 1, so c.x mean a attr of c named 'x'
c.print() --> pirnt 1, so c.print mean a method of c named 'print'
-------------------------------------------------------------------------------------
class C:
    def __init__(self):
        self.x = 1
    def x(self):
        print 'x method'
    def y(self):
        print 'y method'
c = C()
c.x --> 1
c.x() --> TypeError: 'int' object is not callable
c.y --> bound method C.y
#Q1: instance.name will get the attr first, than method?
-------------------------------------------------------------------------------------
class C:
    def x(self):
        print 'x method'
    def __getattr__(self, attr):
        print 'in __getattr__ method'
        return attr
c = C()
c.x --> print in __getattr__ method, then throw TypeError: 'str'
object is not callable
c.x() --> print in __getattr__ method, x method 2 lines
#Q2: why c.x would get a exception?

t = c.x
t --> print in __getattr__ method, then throw TypeError: 'str' object
is not callable
t() --> print x method
t = c.x() --> print x method, t == None
#Q3 why t=c.x() and c.x() output different?

#Q4, if when I define the class use property too, then instance.name
look up order would be?

Thanks for your reply.



More information about the Python-list mailing list