[英]Q: Python package structure with base classes
I am wondering if there is a way to do what I am trying, best explained with an example: 我想知道是否有一种方法可以做我想做的事,最好用一个例子来解释一下:
Contents of a.py: a.py的内容:
class A(object):
def run(self):
print('Original')
class Runner(object):
def run(self):
a = A()
a.run()
Contents of b.py: b.py的内容:
import a
class A(a.A):
def run(self):
# Do something project-specific
print('new class')
class Runner(a.Runner):
def other_fcn_to_do_things(self):
pass
Basically, I have a file with some base classes that I would like to use for a few different projects. 基本上,我有一个包含一些基类的文件,我想将它们用于几个不同的项目。 What I would like would be for
b.Runner.run()
to use the class A
in b.py
, without needing to override the run
method . 我想要的是让
b.Runner.run()
在b.py
使用类A
, 而无需覆盖run
方法 。 In the example above, I would like to code 在上面的示例中,我想编码
import b
r = b.Runner()
print(r.run())
to print "new class". 打印“新班级”。 Is there any way to do that?
有什么办法吗? Is it really awful practice to do that, and is there a better way to structure the code?
这样做真的很糟糕吗,并且有更好的方法来组织代码吗?
This seems a little convoluted. 这似乎有点令人费解。 The Runner classes are probably unnecessary, unless there's something else more complex going on that was left out of your example.
除非您的示例中没有进行其他更复杂的操作,否则Runner类可能是不必要的。 If you're set on not overriding the original
run()
, you could call it in another method in B. Please take a look at this post and this post on super()
. 如果设置为不覆盖原始
run()
,则可以在B中的另一种方法中调用它。请查看这篇文章以及super()
上的这篇文章 。
It would probably make more sense to do something like this: 做这样的事情可能更有意义:
a.py: a.py:
class A(object):
def run(self):
# stuff
print ('Original')
b.py: b.py:
import a
class B(A):
def run(self):
return super(A, self).run()
# can also do: return A.run()
def run_more(self):
super(A, self).run()
# other stuff
print('new class')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.