gue*_*tli 3 python inheritance class-method
我在这个答案中偶然发现了术语“可继承的替代构造函数”:/sf/answers/116866711/
该链接指向一个classmethod进行解释的地方。
其他编程语言也有这个功能吗?
使用任何具有类方法(或类似方法)的语言可以做的事情之一就是提供替代构造函数。下面是一个稍微做作的 Python3 示例:
class Color():
def __init__( self, red, green, blue):
self._red, self._green, self._blue = red, green, blue
@classmethod
def by_name( cls_, color_name ):
color_defs = {'white':(255,255,255), 'red':(255,0,0),
'green':(0,255,0),'blue':(0,0,255)}
return cls_( *color_defs[color_name] )
Run Code Online (Sandbox Code Playgroud)
通过这个课程,您现在可以执行以下操作:
red = Color(255,0,0) # Using the normal constructor
# or
red = Color.by_name('red') # Using the alternative
Run Code Online (Sandbox Code Playgroud)
在 Python 中,“by_name”方法通常被称为工厂方法,而不是构造函数,但它使用普通的构造函数方法。
因为这个“by_name”方法只是一个类方法,这意味着您可以对它进行子类化,该类方法也是继承的 - 因此它可以在任何子类上使用:即它是可继承和可扩展的。
Python 中的子类示例,它扩展了上面的 Color 类,并扩展了构造函数和“by_name”
class ColorWithAlpha( Color ):
def __init__(self, red, green, blue, alpha=1.0):
super().__init__(red,green,blue)
self._alpha = alpha
@classmethod
def by_name( cls_, color_name, alpha):
inst = super().by_name(color_name)
inst._alpha = alpha
return inst
red_alpha = ColorWithAlpha(255,0,0,0.5)
red2_alpha = ColorWithAlpha.by_name('red',0.5)
Run Code Online (Sandbox Code Playgroud)
其他语言也有类似的替代构造函数(例如 C++ 允许基于参数类型的多个构造函数),并且这些方法都是可继承的(即子类也可以使用它们(或根据需要扩展它们)。我不能谈论其他语言,但我确信其他 OOP 语言也将具有类似的构造函数/工厂方法功能。
| 归档时间: |
|
| 查看次数: |
1055 次 |
| 最近记录: |