我应该使用类名还是 `cls` 参数来构造一个实例?

zha*_*gqy 2 python

正如标题所述,我以困惑为例:

class Point(object):

    def __init__(self, x=0.0, y=0.0):
        self.x, self.y = x, y

    @classmethod
    def get_point1(cls, cor): # cor is list with x=1 and y=2
        return Point(cor[0], cor[1])

    @classmethod
    def get_point2(cls, cor):
        return cls(cor[0], cor[1])
Run Code Online (Sandbox Code Playgroud)

我很困惑我应该使用哪个(get_point1get_point2),它们之间有什么区别?

Che*_* A. 6

@classmethod 装饰器使函数成为类方法,而不是实例方法。为了使它更健壮,最好使用cls而不是定义它的实际类名。

如果您使用cls,则在显式使用Point 时将传递的参数取决于被调用的实际类(例如,如果您子类化 Point),如果您子类化它并使用类方法可能会导致问题。

例如看这个代码

class Point(object):

    def __init__(self, x=0.0, y=0.0):
        self.x, self.y = x, y

    @classmethod
    def get_point1(cls, cor): # cor is list like [1,2] with x=1 and y=2
        return Point(cor[0], cor[1])

    @classmethod
    def get_point2(cls, cor):
        return cls(cor[0], cor[1])


class SubPoint(Point):
    pass


sub1 = SubPoint.get_point1([0, 1])
sub2 = SubPoint.get_point2([2, 2])

print sub1.__class__
print sub2.__class__

<class '__main__.Point'>
<class '__main__.SubPoint'>
Run Code Online (Sandbox Code Playgroud)

还有其他区别吗?- 好吧,如果你需要在你的类方法中做一些取决于类属性的逻辑,那么是的。