class A(object):
def xx():
# do something
def yy():
# do something
class B(A):
def func():
# do something
# How to make it possible?
a = A()
a.func()
现在,我想将func()添加到类A,但是我不能更改类A,因此我创建了A的子类,并将func()添加到该子类。如何从实例调用func()?
我尝试从B类开始,但是有很多实例,因此我需要更改许多位置。有更好的方法吗?理想的是A级。
# This works, however, I need to change A() to B() everywhere.
# Are there easy ways to do it without changing A() to B()?
a = B()
a.func()
答案 0 :(得分:1)
您可以使用setattr()
(doc):
class A:
def xx(self):
print('xx')
def yy(self):
print('yy')
class B(A):
def func(self):
print('func')
setattr(A, 'func', B.func) # or setattr(A, B.func.__name__, B.func)
a = A()
a.func()
打印:
func
答案 1 :(得分:-1)