我应该在这个 Python 场景中使用抽象方法吗?
我不确定我的方法是否是好的设计,我希望我能得到提示。我正在考虑抽象方法的某个地方,但在这种情况下我希望该方法是可选的。这就是我现在正在做的...
from pymel.core import *
class A(object):
def __init__(self, *args, **kwargs):
if callable(self.createDrivers):
self._drivers = self.createDrivers(*args, **kwargs)
select(self._drivers)
class B(A):
def createDrivers(self, *args, **kwargs):
c1 = circle(sweep=270)[0]
c2 = circle(sweep=180)[0]
return c1, c2
b = B()
在上面的示例中,我只是在 PyMEL for Maya 中创建 2 个圆弧,但我完全打算创建更多可能有或可能没有 createDrivers 方法的子类!所以我希望它是可选的,我想知道我的方法是否可以改进?
I'm not sure my approach is good design and I'm hoping I can get a tip. I'm thinking somewhere along the lines of an abstract method, but in this case I want the method to be optional. This is how I'm doing it now...
from pymel.core import *
class A(object):
def __init__(self, *args, **kwargs):
if callable(self.createDrivers):
self._drivers = self.createDrivers(*args, **kwargs)
select(self._drivers)
class B(A):
def createDrivers(self, *args, **kwargs):
c1 = circle(sweep=270)[0]
c2 = circle(sweep=180)[0]
return c1, c2
b = B()
In the above example, I'm just creating 2 circle arcs in PyMEL for Maya, but I fully intend on creating more subclasses that may or may not have a createDrivers method at all! So I want it to be optional and I'm wondering if my approach is—well, if my approach could be improved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您继承类 B 时,您仍然遇到问题,这将调用
A.__init__
并且如果您没有在子类中实现createDrivers
,则此行callable(self.createDrivers)
会抛出错误,因为createDrivers
不存在(AttributeError)我想如果我是你我会这样做:另一种方法是替换
callable(self.createDrivers)
通过hasattr(self, 'createDrivers')
。You still have a problem, when you will inherit your class B, and this will call
A.__init__
and if you don't implementcreateDrivers
in the subclass this linecallable(self.createDrivers)
will throw an error as thatcreateDrivers
doesn't exist (AttributeError) i think if i were you i will do it like so:Another way is to replace
callable(self.createDrivers)
byhasattr(self, 'createDrivers')
.我会这样做:
I would do this:
如果您希望 createDrivers 是可选的但仍然始终存在,那么最好的不是抽象方法,而是在基类中将其实现为 noop。
If you want createDrivers to be optional but still always there, the best is not an abstract method, but do implement it in the base class as a noop.