Python中继承子方法
我想继承 python 中方法的“子方法”。有人可以帮我弄清楚该怎么做吗?
我想做的示例:
class A(object):
def method(self, val):
def submethod():
return "Submethod action"
if not val:
return submethod()
return "Method action"
a = A()
class B(A):
def method(self, val):
#inherit submethod ?
def submethod():
return "Another submethod action"
return super(B,self).method(val)
b = B()
print "A : "
print a.method(True)
>> Method action
print a.method(False)
>> Submethod action
print "B : "
print b.method(True)
>> Method Action
print b.method(False)
Actual answer :
>> Submethod Action
**Wanted answer :
>> Another submethod action**
亲切的问候,
昆汀
I would like inherit a 'submethod' of a method in python. Could somebody help me to figure out how to do this please ?
Example of what I want to do :
class A(object):
def method(self, val):
def submethod():
return "Submethod action"
if not val:
return submethod()
return "Method action"
a = A()
class B(A):
def method(self, val):
#inherit submethod ?
def submethod():
return "Another submethod action"
return super(B,self).method(val)
b = B()
print "A : "
print a.method(True)
>> Method action
print a.method(False)
>> Submethod action
print "B : "
print b.method(True)
>> Method Action
print b.method(False)
Actual answer :
>> Submethod Action
**Wanted answer :
>> Another submethod action**
Kind regards,
Quentin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法“继承”
submethod
,因为它是method
的本地变量,并且在method
运行之前根本不存在。为什么不简单地将其作为
A
和B
的顶级方法呢?You can't "inherit"
submethod
since it's local tomethod
and doesn't even exist untilmethod
is run.Why not simply make it a top-level method of
A
andB
?这称为闭包(函数中的函数),其行为与您所要求的不太一样。因为函数不像类,所以它们没有“实例”的概念,因此函数内部的任何对象都不能从外部访问,除非它们由函数返回。
注意,在 Python 中,方法本质上是绑定到类的函数。
这将是一个更好的模式:
您可以访问闭包的内部状态,但这与您正在考虑的属性样式访问不同。在您完全理解 Python 的命名空间、内容和垃圾如何工作之前,最好避免使用它们。
This is called a closure (a function within a function) and does not quite behave like what you're asking. Because functions are not like classes, they do not have the concept of "instances", and therefore any objects internal to the function are not externally accessible unless they are
return
ed by the function.NB, In Python methods are essentially functions that are bound to a class.
This would be a better pattern:
You may access internal state of closures, but it's not the same as attribute-style access you're thinking. It's better to avoid them until you fully understand how Python's namespaces and stuff and junk work.