【问题标题】:constructor and method overriding in PythonPython中的构造函数和方法覆盖
【发布时间】:2016-07-21 19:50:00
【问题描述】:

我想弄清楚是否有办法覆盖 python 类中的__init__ 方法。我想出了这个,不完全是方法覆盖,但它具有相同的效果

class A():
    def __init__(self, x):
        if isinstance(x, str):
            print "calling some text parsing method"
        elif isinstance(x, int):
            print "calling some number crunching method"
        else:
            print "Oops"

请问这是好的做法吗?不仅适用于这个特定问题中的构造函数,也适用于其他方法

【问题讨论】:

    标签: python methods constructor overriding


    【解决方案1】:

    如果字符串参数的操作与整数参数的操作非常不同,那么这基本上就是您需要做的。但是,如果一种情况归结为另一种情况,那么您可以将类方法定义为备用构造函数。作为一个简单的例子,考虑

    class A():
        def __init__(self, x):
            if isinstance(x, str):
                self.x = int(x)
            elif isinstance(x, int):
                self.x = x
            else:
                raise ValueError("Cannot turn %s into an int" % (x, ))
    

    这里,整数大小写是创建A实例的“基本”方式;字符串大小写简化为将字符串转换为整数,然后按整数大小写处理。您可以将其重写为

    class A():
        # x is expected to be an integer
        def __init__(self, x):
            self.x = x
    
        # x is expected to be a string
        @classmethod
        def from_string(cls, x):
            try:
                return cls(int(x))
            except ValueError:
                # This doesn't really do anything except reword the exception; just an example
                raise ValueError("Cannot turn %s into an int" % (x, ))
    

    通常,您希望避免检查值的类型,因为类型不如行为重要。例如,上面的from_string 并不需要字符串;它只是期望可以变成int 的东西。那可能是str 或float。

    【讨论】:

      猜你喜欢
      • 2013-03-01
      • 1970-01-01
      • 2016-02-27
      • 2021-03-18
      • 2014-05-22
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 2014-04-11
      相关资源
      最近更新 更多