Python 从使用类型函数创建的实例调用基类方法
通常,Python中的基类方法可以从派生类调用,调用方式与调用任何派生类函数相同:Python 从使用类型函数创建的实例调用基类方法,python,python-3.x,Python,Python 3.x,通常,Python中的基类方法可以从派生类调用,调用方式与调用任何派生类函数相同: class Base: def base_method(self): print("Base method") class Foo(Base): def __init__(self): pass f = Foo() f.base_method() 但是,当我使用type函数动态创建类时,如果不传入self实例,我将无法调用基类方法: class Base:
class Base:
def base_method(self):
print("Base method")
class Foo(Base):
def __init__(self):
pass
f = Foo()
f.base_method()
但是,当我使用type
函数动态创建类时,如果不传入self
实例,我将无法调用基类方法:
class Base:
def base_method(self):
print("Base method")
f = type("Foo", (Base, object), { "abc" : "def" })
f.base_method() # Fails
这会引发一个TypeError:TypeError:base_method()正好接受一个参数(给定0)
如果我显式地传递一个self
参数,它就会工作:
f.base_method(f)
调用基类方法时,为什么需要显式传递self
实例?您的行f=type(…)
返回的是类,而不是实例
如果您执行f().base\u method()
,它应该可以工作。您的行f=type(…)
返回一个类,而不是一个实例
如果您执行
f().base\u method()
,它应该可以工作。type
返回类而不是实例。在调用base\u方法之前,应该实例化该类:
>>> class Base(object):
... def base_method(self): print 'a'
...
>>> f = type('Foo', (Base,), {'arg': 'abc'})
>>> f.base_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method base_method() must be called with Foo instance as first argument (got nothing instead)
>>> f().base_method()
a
>>类基(对象):
... def base_方法(自身):打印“a”
...
>>>f=type('Foo',(Base,),{'arg':'abc'})
>>>f.基本方法()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:必须使用Foo实例作为第一个参数调用未绑定的方法base_method()(但没有得到任何结果)
>>>f().base_方法()
A.
类型
返回类而不是实例。在调用base\u方法之前,应该实例化该类:
>>> class Base(object):
... def base_method(self): print 'a'
...
>>> f = type('Foo', (Base,), {'arg': 'abc'})
>>> f.base_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method base_method() must be called with Foo instance as first argument (got nothing instead)
>>> f().base_method()
a
>>类基(对象):
... def base_方法(自身):打印“a”
...
>>>f=type('Foo',(Base,),{'arg':'abc'})
>>>f.基本方法()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:必须使用Foo实例作为第一个参数调用未绑定的方法base_method()(但没有得到任何结果)
>>>f().base_方法()
A.
在第二个示例中,使用类Foo(Base):…
毫无意义。可能是剪切粘贴错误。@Bakuriu--可能是。我只是想指出这一点。根据OP对type
的确切想法,他可能会认为这是必要的,而且f
和类Foo
是相关的(因为它们毕竟有相同的\uuu名称。\uuuuuu
),没有类Foo(Base)的意义:…
在第二个示例中。可能是剪切粘贴错误。@Bakuriu——可能是。我只是想指出这一点。根据OP对type
的确切想法,他可能会认为这是必要的,并且f
和类Foo
是相关的(因为它们毕竟有相同的\uuuu名称)。