在python中调用类时在类中调用函数

我想要徽章

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

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

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

dotheprint(self)

但是我不明白为什么。我应该对类进行哪些更改,以使用已包含的数据来运行该函数?(细绳)

马丁·彼得斯(Martijn Pieters)

您会误解类的工作原理。您可以将调用放入类定义主体中;当时没有实例,也没有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()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章