【发布时间】:2020-08-07 14:27:39
【问题描述】:
我想构建一个类和子类,其中子类从超类继承一些方法。
到目前为止没有什么特别的,但我希望能够根据参数创建子类,例如a = Shape(sides=3, base=2, height=12) 应该与示例代码中的 c = Triangle(base=2, height=2) 相同:
class Shape:
def __new__(cls, sides, *args, **kwargs):
if sides == 3:
print('a')
return Triangle(*args, **kwargs)
else:
return Square(*args, **kwargs)
def __init__(self, a):
self._a = a
@property
def a(self):
return self._a
class Triangle(Shape):
def __init__(self, base, height):
super().__init__(self, a='triangle')
self.base = base
self.height = height
def area(self):
return (self.base * self.height) / 2
class Square(Shape):
def __init__(self, length):
Shape.__init__(self, a='square')
self.length = length
def area(self):
return self.length * self.length
a = Shape(sides=3, base=2, height=12)
b = Shape(sides=4, length=2)
c = Triangle(base=2, height=2)
print(c.a)
print(str(a.__class__))
print(a.area())
print(str(b.__class__))
print(b.area())
这会引发错误TypeError: __new__() missing 1 required positional argument: 'sides'。
当我不继承类(做class Triangle:)时,它不会抛出错误,但我当然不能再使用函数a...
有什么提示吗?到目前为止,我的解决方案是基于 https://stackoverflow.com/a/60769071、https://stackoverflow.com/a/61509283 和 https://www.code-learner.com/how-to-use-python-new-method-example/
一种可能是使用工厂模式,但我真的很喜欢覆盖 new 函数的想法...
【问题讨论】:
标签: python python-3.x inheritance subclass