Python 类中的作用域
请看一下:
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
是全局的。
谢谢
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 bid_it
is global.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过使用
self
,您已将其绑定到实例。它现在是一个实例变量。实例变量是其实例的本地变量。如果变量未绑定(无 self 前缀),则它具有函数作用域,并在方法调用结束后超出作用域,但您已将其绑定到其他内容(实例)。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).“self”的作用类似于 C++ 中的 this 指针,在本例中是对 Car 对象的引用。如果 bid_it 未在 self 中定义,则会动态创建并分配一个值。这意味着您可以在任何地方创建它,只要您有对象的引用即可。
'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.