0

这个简单的例子是我在更复杂的脚本中无法工作或理解的:

class printclass():
    string="yes"
    def dotheprint(self):
        print self.string
    dotheprint(self)
printclass()

调用该类时,我希望它运行该函数,但它会告诉我“未定义自我”。我知道这在线上发生:

dotheprint(self)

但我不明白为什么。我应该对类进行哪些更改才能使用其中已有的数据运行函数?(细绳)

4

2 回答 2

3

您误解了课程的运作方式。您将调用放在类定义主体中;当时没有实例,没有self.

调用实例上的方法:

instance = printclass()
instance.dotheprint()

现在dotheprint()方法被绑定了,有一个实例self可以引用。

如果需要dotheprint()在创建实例时调用,请给类一个__init__方法。每当您创建实例时,都会调用此方法(初始化程序):

class printclass():
    string="yes"

    def __init__(self):
        self.dotheprint()

    def dotheprint(self):
        print self.string

printclass()
于 2013-10-01T08:46:15.233 回答
1

你真的需要理解Object-Oriented Programming它在 Python 中的实现。你不能像任何函数一样“调用”一个类。您必须创建一个实例,该实例具有生命周期和与之链接的方法:

o = printclass() # new object printclass
o.dotheprint()   # 

更好地实现您的课程

class printclass():
    string="yes"         #beware, this is instance-independant (except if modified later on)

    def dotheprint(self):
        print self.string

    def __init__(self):  # it's an initializer, a method called right after the constructor
         self.dotheprint()
于 2013-10-01T08:51:37.293 回答