什么是“可继承的替代构造函数"? [英] What are "inheritable alternative constructors"?

查看:88
本文介绍了什么是“可继承的替代构造函数"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个答案中,我偶然发现了可继承的替代构造函数"一词: https://stackoverflow. com/a/1669524/633961

I stumbled over the term "inheritable alternative constructors" in this answer: https://stackoverflow.com/a/1669524/633961

链接指向解释classmethod的地方.

其他编程语言也具有此功能吗?

Do other programming languages have this feature, too?

推荐答案

使用具有类方法(或类似方法)的任何语言都可以做的一件事是提供替代构造函数.下面是一个人为设计的Python3示例:

One of the things that you can do with ANY language that has class methods (or similar) is provide alternative constructors. A slightly contrived Python3 example below :

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] )

有了这个课程,您现在可以做到:

with this class you can now do :

    red = Color(255,0,0) # Using the normal constructor
    # or
    red = Color.by_name('red') # Using the alternative 

在Python中,"by_name"方法通常称为工厂方法,而不是构造方法,但它使用常规的构造方法.

In Python the 'by_name' method would normally be called a factory method, rather than a constructor, but it uses the normal constructor methods.

因为此"by_name"方法只是一个类方法,它意味着您将其子类化,所以该类方法也继承了-因此它可以在任何子类上使用:即,它是可继承和可扩展的.

Because this 'by_name' method is just a classmethod, it means you subclass it, the class method is inherited too - so it can be used on any subclass: i.e. it is inheritable and extensible.

Python中一个子类的示例,该子类扩展了上面的Color类,并扩展了构造函数和'by_name'

An example in Python of a subclass which extends the Color class above, and extends the constructor and the '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)

其他语言具有类似的替代构造函数(例如C ++允许基于参数类型的多个构造函数),并且这些方法都是可继承的(即子类也可以使用它们(或根据需要扩展它们)). 我不会说其他语言,但是我确定其他OOP语言将具有类似的构造函数/工厂方法功能.

Other languages have similar alternative constructors (for instance C++ allows multiple constructors based on the arguments types), and these methods are all inheritable (i.e. subclasses can use them too (or extend them as necessary). I can't speak of other languages, but I am sure other OOP languages will have similar constructors/factory method capabilities.

这篇关于什么是“可继承的替代构造函数"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆