-5

我试图从一个方法中的一个类中引用一个变量,我在没有 self 的情况下尝试了它,但是这给了我错误“名称 'one' 没有定义”。

class hello(object):
    self.one = 1
    def method(self):
        print one

food = hello()
food.method()
4

2 回答 2

11

你想定义一个类变量还是一个实例变量?

对于在实例/对象范围内定义的变量,请使用:

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()
于 2014-01-04T16:44:36.193 回答
-2

它应该是print self.one代替print oneone = 1代替self.one = 1

于 2014-01-04T16:39:29.110 回答