Python中类的范围

时间:2011-05-02 20:00:31

标签: python scope function

请看一下:

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()

bid_it的范围是什么?我认为它是一个局部变量,因为它位于def块内。我怎么可能在函数之外调用它?我没有宣称bid_it是全球性的。

由于

2 个答案:

答案 0 :(得分:5)

通过使用self,您已将其绑定到实例。它现在是一个实例变量。实例变量是其实例的本地变量。如果变量是未绑定的(没有自己的前缀),那么一旦方法调用结束,它就会有函数范围并超出范围,但是你已将它绑定到其他东西(实例)。

答案 1 :(得分:0)

def doit(self, cry):
    self.bid_it = cry

'self'在c ++中就像一个this指针,在这种情况下是对Car对象的引用。如果未在self中定义bid_it,则会动态创建并分配值。这意味着您可以在任何地方创建它,只要您有对象的引用即可。