Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我应该使用类名或'cls`param来构造实例吗?_Python - Fatal编程技术网

Python 我应该使用类名或'cls`param来构造实例吗?

Python 我应该使用类名或'cls`param来构造实例吗?,python,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

如标题所述,我将其作为示例:

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

我不知道应该使用哪一种(
get_point1
get_point2
),它们之间有什么区别?

与实例方法相反,@classmethod decorator使函数成为类方法。为了使它更加健壮,最好使用
cls
,而不是定义它的实际类名

如果使用cls,将传递的参数取决于在使用Point明确性时调用的实际类(例如,如果对Point进行子类化),如果对其进行子类化并使用class方法,则可能会导致问题

以这段代码为例

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'>
类点(对象):
定义初始化(self,x=0.0,y=0.0):
self.x,self.y=x,y
@类方法
def get_point1(cls,cor):#cor是类似于[1,2]的列表,x=1,y=2
返回点(cor[0],cor[1])
@类方法
def get_点2(cls,cor):
返回cls(对应[0],对应[1])
类子点(点):
通过
sub1=子点。获取_点1([0,1])
sub2=子点。获取_点2([2,2])
打印子1.\u类__
打印子2.\u类__

还有其他区别吗?-如果您需要在类方法内部执行一些逻辑,这取决于类属性,那么是的。

考虑一下,如果您将
指向
子类,并在子类上调用这些方法,会发生什么。您应该使用哪个取决于您想要的行为。
cls()
是首选,因为它允许您扩展该类。例如,
类特殊点(点):pass
。当前,
SpecialPoint.get\u point1(cor)
将创建一个
Point
对象,而
SpecialPoint.get\u point2(cor)
将创建一个
SpecialPoint
。谢谢,除了子类之外还有其他区别吗?其中一个可能是,如果将来更改类的名称,您只需要更改一次(在顶部)而不是在每个类方法中。
cls()
如果要将
Point
子类化,则肯定是有意义的。如果您认为最终可能会将其子类化,则可能会有意义。如果这两种情况都不是这样,则使用
Point()
更显式和可读。