我试图从一个方法中的一个类中引用一个变量,我在没有 self 的情况下尝试了它,但是这给了我错误“名称 'one' 没有定义”。
class hello(object):
self.one = 1
def method(self):
print one
food = hello()
food.method()
我试图从一个方法中的一个类中引用一个变量,我在没有 self 的情况下尝试了它,但是这给了我错误“名称 'one' 没有定义”。
class hello(object):
self.one = 1
def method(self):
print one
food = hello()
food.method()
你想定义一个类变量还是一个实例变量?
对于在实例/对象范围内定义的变量,请使用:
class hello(object):
def __init__(self):
self.one = 1
def method(self):
print self.one
food = hello()
food.method()
对于类变量:
class hello(object):
one = 1
def method(self):
print hello.one
food = hello()
food.method()
它应该是print self.one
代替print one
和one = 1
代替self.one = 1