在派生 class 之外使用派生 class 对象调用基本 class 方法
call a base class method using a derived class object outside the derived class
我看过很多描述如何调用 base class 函数的帖子 is called inside a derived class function using the super keyword.I want to call a base class 使用派生的 class 对象全局重载函数。
class a:
def __init__(self):
self.x=45
def fun(self):
print "fun in base class"
class b(a):
def __init__(self):
self.y=98
def fun(self):
print "fun in derived class"
objb=b()
objb.fun()#here i want to call the base class fun()
输入:
objb = b()
super(b, objb).fun()
输出:
fun in base class
编辑:
正如下面评论中提到的,在 Python 2.7+ 中你需要声明 class a(object)
才能工作。这来自 Python 中 类 的历史演变,此解决方案仅适用于 "new-style" 类,即 类 继承自 object
.但是,在 Python 3.x 中,默认情况下所有 类 都是 "new-style",这意味着您不必执行这个小加法。
如果你真的想调用适用于旧式 classes(classes 不扩展 object
)的 'base' 函数,你可以这样做:
objb = b()
a.fun(objb) # fun in base class
或者,如果您不知道 base/parent class,您可以 'extract' 从实例本身:
objb = b()
objb.__class__.__bases__[0].fun(objb) # fun in base class
但省去一些麻烦,只需从 object
扩展基数 classes,这样您就可以使用 super()
符号而不是 bases 杂技.
我看过很多描述如何调用 base class 函数的帖子 is called inside a derived class function using the super keyword.I want to call a base class 使用派生的 class 对象全局重载函数。
class a:
def __init__(self):
self.x=45
def fun(self):
print "fun in base class"
class b(a):
def __init__(self):
self.y=98
def fun(self):
print "fun in derived class"
objb=b()
objb.fun()#here i want to call the base class fun()
输入:
objb = b()
super(b, objb).fun()
输出:
fun in base class
编辑:
正如下面评论中提到的,在 Python 2.7+ 中你需要声明 class a(object)
才能工作。这来自 Python 中 类 的历史演变,此解决方案仅适用于 "new-style" 类,即 类 继承自 object
.但是,在 Python 3.x 中,默认情况下所有 类 都是 "new-style",这意味着您不必执行这个小加法。
如果你真的想调用适用于旧式 classes(classes 不扩展 object
)的 'base' 函数,你可以这样做:
objb = b()
a.fun(objb) # fun in base class
或者,如果您不知道 base/parent class,您可以 'extract' 从实例本身:
objb = b()
objb.__class__.__bases__[0].fun(objb) # fun in base class
但省去一些麻烦,只需从 object
扩展基数 classes,这样您就可以使用 super()
符号而不是 bases 杂技.