Scopes in a class in Python
Please have a look at this:
class Car:
def __init__(self, bid_code):
self.__bid = bid_code
def doit(self, cry):
self.bid_it = cry
def show_bid(self):
print self.__bid
def show_it(self):
print self.bid_it
a = Car("ok")
a.show_bid()
a.doit("good")
a.show_it()
What is the scope of bid_it
here? I thought it was a local variable, because it is inside a def
block. How is it possible that I can call it outside the function? I haven't declared that bi开发者_高级运维d_it
is global.
Thanks
By using self
, you've bound it to the instance. It's now an instance variable. Instance variables are local to their instances. If the variable were unbound (no self prefix), it'd have function scope and go out of scope once the method call is over, but you've bound it to something else (the instance).
def doit(self, cry):
self.bid_it = cry
'self' acts like a this pointer in c++, in this case a reference to a Car object. If bid_it is not defined in self, it's created on the fly and assigned a value. This means that you can create it anywhere, just as long as you have a reference to your object.
精彩评论