繁体   English   中英

python:使用或不使用引用访问类变量

[英]python: accessing class variable with or without reference

码:

class Example:

    pos_list=[]
    last_cell=0

    def setText(self):
        last_cell = 10
        pos_list.append(int(10))              #Line 1
        print pos_list , last_cell            #Line 2

错误:未定义全局名称“ pos_list”。

如果我在第1行和第2行中访问pos_list

   self.pos_List or Example.pos_list

然后没有错误[这很好,因为我可以作为instance(self)或class(Example)变量来访问它]

但是last_cell呢? 我在没有自我或班级参考的情况下访问它。 但是在pos_list的情况下,python解释器迫使我使用这两个引用中的任何一个。

为什么没有参考就可以访问last_cell?

你不是 您只是在创建一个碰巧具有相同名称的局部变量。

class Example:
    x = 1
    def f(self):
        x = 2
Example().f()
print(Example.x) #=> 1

因为您将last_cell声明为局部变量。 在执行pos_list.append()您尝试在未定义的对象上调用方法,这会产生错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM