简体   繁体   English

Python中的构造函数和方法重写

[英]constructor and method overriding in Python

I am trying to figure out if there is a way to override the __init__ method in a python class. 我试图找出是否有一种方法可以覆盖python类中的__init__方法。 I have come up with this, not exactly method overriding but it has the same effect 我想出了这个,不是完全方法重写,但它具有相同的效果

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"

Is this good practice please? 请问这是好习惯吗? Not only for constructors as in this particular question but also for other methods too 不仅针对此特定问题的构造函数,还针对其他方法

That's essentially what you need to do, if the actions for a string argument are very different from the actions for an integer argument. 如果字符串参数的操作与整数参数的操作有很大不同,那基本上就是您需要做的。 However, if one case reduces to the other, then you can define a class method as an alternate constructor. 但是,如果一种情况减少到另一种情况,则可以将类方法定义为备用构造函数。 As an simple example, consider 作为一个简单的例子,考虑

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

Here, the integer case is the "fundamental" way to create an instance of A ; 在这里,整数大小写是创建A实例的“基本”方法; the string case reduces to turning the string into an integer, then proceding as in the integer case. 字符串大小写简化为将字符串转换为整数,然后像整数大小写一样进行处理。 You might rewrite this as 您可以将其重写为

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

In general, you want to avoid checking for the type of a value, because types are less important than behavior. 通常,您要避免检查值的类型,因为类型不如行为重要。 For example, from_string above doesn't really expect a string; 例如,上面的from_string并不真正期望一个字符串。 it just expects something that can be turned into an int . 它只是期望可以转化为int That could be a str or a float . 可能是strfloat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM