在python中调用类时调用类内的函数
这个简单的例子是我在更复杂的脚本中无法工作或理解的:在python中调用类时调用类内的函数,python,function,class,Python,Function,Class,这个简单的例子是我在更复杂的脚本中无法工作或理解的: class printclass(): string="yes" def dotheprint(self): print self.string dotheprint(self) printclass() 调用该类时,我希望它运行函数,但它会告诉我“self未定义”。我知道这是在网上发生的: dotheprint(self) 但我不明白为什么。我应该改变什么,让类使用它已经包含的数据运行函数?(字符
class printclass():
string="yes"
def dotheprint(self):
print self.string
dotheprint(self)
printclass()
调用该类时,我希望它运行函数,但它会告诉我“self未定义”。我知道这是在网上发生的:
dotheprint(self)
但我不明白为什么。我应该改变什么,让类使用它已经包含的数据运行函数?(字符串)您误解了类的工作方式。您将调用放在类定义体中;当时没有实例,没有
self
调用实例上的方法:
instance = printclass()
instance.dotheprint()
class printclass():
string="yes"
def __init__(self):
self.dotheprint()
def dotheprint(self):
print self.string
printclass()
现在绑定了dotheprint()
方法,有一个self
实例可供参考
如果在创建实例时需要调用dotheprint()
,请为类提供一个\uuuu init\uuuu
方法。无论何时创建实例,都会调用此方法(初始值设定项):
instance = printclass()
instance.dotheprint()
class printclass():
string="yes"
def __init__(self):
self.dotheprint()
def dotheprint(self):
print self.string
printclass()
你误解了课堂的运作方式。您将调用放在类定义体中;当时没有实例,没有
self
调用实例上的方法:
instance = printclass()
instance.dotheprint()
class printclass():
string="yes"
def __init__(self):
self.dotheprint()
def dotheprint(self):
print self.string
printclass()
现在绑定了dotheprint()
方法,有一个self
实例可供参考
如果在创建实例时需要调用dotheprint()
,请为类提供一个\uuuu init\uuuu
方法。无论何时创建实例,都会调用此方法(初始值设定项):
instance = printclass()
instance.dotheprint()
class printclass():
string="yes"
def __init__(self):
self.dotheprint()
def dotheprint(self):
print self.string
printclass()
您确实需要了解面向对象编程及其在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()
您确实需要了解面向对象编程及其在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()
\uuuu init\uuuu
不是构造函数。它不构造实例。它是一个初始值设定项;在已构造项之后调用它<代码>\uuuu new\uuuu是构造函数。哦,你说得对。由于Python中没有任何内存管理,我几乎不使用new。我会修正我的答案。不是构造函数。它不构造实例。它是一个初始值设定项;在已构造项之后调用它<代码>\uuuu new\uuuu
是构造函数。哦,你说得对。由于Python中没有任何内存管理,我几乎不使用new。我会修正我的答案。