简体   繁体   English

类与静态方法

[英]class vs static methods

I'm new in Python (come from C#), trying to figure out how OOP works here. 我是Python的新手(来自C#),试图弄清楚OOP在这里是如何工作的。 Started from very begining I try to implement Vector class. 从一开始我就尝试实现Vector类。 I want to have basis vectors (i, j, k) defined in Vector class. 我想在Vector类中定义基向量(i,j,k)。 In C#, I can do this like that: 在C#中,我可以这样做:

public class Vector
{
    // fields...
    public Vector(int[] array){
        //...
    }

    public static Vector i(){
        return new Vector(new int[1, 0, 0]);
    }
}

Exploring Python I found 2 ways how to implement this: using either @classmethod or @staticmethod : 在研究Python时,我发现了两种实现方法:使用@classmethod@staticmethod

class Vector:
    def __init__(array):
        #...

    @classmethod
    def i(self):
        return Vector([1, 0, 0])

Since I don't need to have access to any information inside the class, should I really use @classmethod ? 由于我不需要访问类内部的任何信息,因此我真的应该使用@classmethod吗?

I think you've confused yourself with your naming of arguments a bit. 我认为您对参数的命名有些困惑。 The first argument a class method receives is the class itself, which would be Vector, for now, until you have a subclass. 类方法接收的第一个参数是类本身,在您拥有子类之前,它现在是Vector。 A class method would be implemented like this: 一个类方法可以这样实现:

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

Generally, an instance method (no decorator) calls its first argument self , which is the instance. 通常,实例方法(没有装饰器)调用其第一个参数self ,即实例。 A class method has cls , which is the class, which can be used to construct an instance. 一个类方法有cls ,它是类,可用于构造实例。 A static method takes no "extra" argument, so your other option, if you want to always return a Vector , is: 静态方法不带任何“额外”参数,因此,如果要始终返回Vector ,则另一个选择是:

    @staticmethod
    def i():
        return Vector([1, 0, 0])

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

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