Python 使用父类中的方法
我想从子类中的父类调用一个方法 我在我的子类中使用Python 使用父类中的方法,python,class,Python,Class,我想从子类中的父类调用一个方法 我在我的子类中使用XX.\uuuu init\uuu(),并从父类调用press函数。但运行以下代码时失败: Func.py action.py 我得到: unbound method Sentence() must be called with PCFunc instance as first argument (got str instance instead) 您发布的代码不会产生您发布的错误。以下是将产生该错误的示例: class Dog: de
XX.\uuuu init\uuu()
,并从父类调用press函数。但运行以下代码时失败:
Func.py
action.py
我得到:
unbound method Sentence() must be called with PCFunc instance as first argument (got str instance instead)
您发布的代码不会产生您发布的错误。以下是将产生该错误的示例:
class Dog:
def do_stuff(self, string):
print string
d = Dog()
d.do_stuff('hello')
Dog.do_stuff(d, 'goodbye')
Dog.do_stuff('goodbye')
--output:--
hello
goodbye
Traceback (most recent call last):
File "1.py", line 9, in <module>
Dog.do_stuff('goodbye')
TypeError: unbound method do_stuff() must be called with Dog instance as first argument (got str instance instead)
class Dog:
def __init__(self):
pass
def do_stuff(self, string):
print(string)
Dog.__init__()
--output:--
Traceback (most recent call last):
File "1.py", line 7, in <module>
Dog.__init__()
TypeError: unbound method __init__() must be called with Dog instance as first argument (got nothing instead)
行中:
d.do_stuff('hello')
片段d.do_stuff
导致python创建并返回一个绑定的方法对象——然后由片段('hello')
中的函数执行操作符()
立即执行该对象。绑定方法绑定到实例d
,因此它被称为绑定方法。绑定方法在执行该方法时自动将其包含的实例传递给该方法
另一方面,当你写作时:
Dog.do_stuff(....)
片段Dog.dou stuff
导致python创建并返回一个未绑定的方法。未绑定方法不包含实例,因此当函数执行操作符()
执行未绑定方法时,必须手动传递实例。(在python3
中,情况发生了变化,您可以将任何内容作为第一个参数传递——不需要类的实例。)如果您想调用基类的构造函数,那么您可以在\uu init\uuuuuuuuuuu()
方法中进行实例化,而不是在语句()
方法中:
def __init__(self):
super(self.__class__, self).__init__()
由于语句()
是一个实例方法,因此需要通过类的实例调用它(就像错误告诉您的那样):
在这里,您使用未定义的变量调用该方法:
PCFunc.Sentence(path)
相反,您需要提供一个字符串作为参数,因此要么编写语句('path')
,要么首先定义变量:
path = 'my path'
pc_func.Sentence(path)
不要使用与类实例的类名相同的名称:
PCFunc = Func.PCFunc ()
否则,存储实例的变量名将覆盖类名
除此之外,还不清楚您的代码实际应该做什么。请参阅,这是使代码更易于阅读的第一步。然后做一些关于类和继承的研究。您在这里真正想要实现什么?您希望在PCFunc.sense
中调用PC.\uuuu init\uuuu()
做什么?为什么要创建PCFunc
的实例并将其命名为PCFunc
?为什么PCFunc.\uuuu init\uuuu
只是pass
?!到目前为止,您的代码对我来说没有什么意义。直接的问题是,您调用的是PCFunc.句子
,就像调用类方法,而不是类方法。更大的问题是,整个事情几乎毫无意义。
PCFunc.Sentence(path)
path = 'my path'
pc_func.Sentence(path)
PCFunc = Func.PCFunc ()