在Python中使用实例函数覆盖类函数
考虑这个例子:
class master:
@classmethod
def foo(cls):
cls.bar()
class slaveClass( master ):
@classmethod
def bar(cls):
print("This is class method")
slaveType = slaveClass
slaveType.foo()
class slaveInstance( master ):
#def foo(self):
# self.foo()
def __init__(self,data):
self.data=data
print("Instance has been made")
def bar(self):
print("This is "+self.data+" method")
slaveType = slaveInstance("instance")
slaveType.foo()
我知道当 foo
的最后一个定义被取消注释时它可以工作,但是有没有其他方法可以在不改变用法的情况下使用这个 foo
函数。我有一个大型项目,其中类定义了事物的工作方式,并且我能够使用 slaveType
更改方式,但碰巧存在需要实例的情况,并且有太多 foo
类似于要覆盖实例行为的函数。
谢谢各位堆垛机!
Consider this example:
class master:
@classmethod
def foo(cls):
cls.bar()
class slaveClass( master ):
@classmethod
def bar(cls):
print("This is class method")
slaveType = slaveClass
slaveType.foo()
class slaveInstance( master ):
#def foo(self):
# self.foo()
def __init__(self,data):
self.data=data
print("Instance has been made")
def bar(self):
print("This is "+self.data+" method")
slaveType = slaveInstance("instance")
slaveType.foo()
I know it works when last definition of foo
is uncommented, but is there any other way to use this foo
function without changing the usage. I have large project where classes defined the way things worked and I was able to change the way with slaveType
but there happen to be a case where instance is needed, and there is bit too many foo
like functions to be overridden for instance behavior.
Thank you stackers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
仔细查看文档中的 classmethod。实例方法将实例作为第一个参数传递,类方法将类作为第一个参数传递。调用
slaveType.foo()
会传递一个实例slaveType
,作为foo()
的第一个参数。foo()
期望一个类作为第一个参数。Look closer at the doc for classmethod. Instance methods pass an instance as the first argument, and class methods pass a class as the first argument. Calling
slaveType.foo()
passes an instance,slaveType
, as the first argument offoo()
.foo()
is expecting a class as the first argument.