【发布时间】:2014-03-12 11:36:30
【问题描述】:
- 类变量是否在为 Python 类定义的方法的范围内?
- 如何访问方法中的类变量(类方法或实例方法或静态方法)并可能更改它?
- 最好的方法是什么?例如,我可能想计算已经创建了多少个类的实例。
我读到here 说类变量在方法参数列表的范围内。要在那里使用类变量,我应该将其称为counter 而不是MyClass.counter,因为该类正在定义中,但是我可以在__init__ 方法中以MyClass.counter 的形式访问它。这是否意味着在 __init__ 方法中时该类已完全定义?
编辑:我也想知道为什么counter在方法的参数列表范围内,但不在方法体中?
class MyClass(object):
counter = 0
def __init__(self): # counter is in scope here. can be used as default argument
counter += 1 # Counter not in scope. Throws UnboundLocalError
def printCount(self):
print counter # Counter not in scope. Throws UnboundLocalError
【问题讨论】:
-
我问这里是为了解释为什么会这样。
-
你应该得到
UnboundLocalError错误而不是全局错误。 -
UnboundLocalError: local variable 'counter' referenced before assignment. -
因此,如果您阅读链接到的答案,您会注意到回答者从未在方法主体内引用
counter... 所以不,除非您在课堂上提及它,否则它不在范围内名字。 -
当类主体完成执行后,变量
counter已转换为Myclass.counter,因此要在方法中访问该变量,您需要使用类名或self。跨度>
标签: python class methods scope