类和实例方法之间的差异[duplicate]

时间:2022-04-15 22:27:17

This question already has an answer here:

这个问题已经有了答案:

I was reading PEP 0008 (Style Guide), and I noticed that it suggested to use self as the first argument in an instance method, but cls as the first argument in a class method.

我正在阅读PEP 0008 (Style Guide),我注意到它建议将self作为实例方法中的第一个参数,而将cls作为类方法的第一个参数。

I've used and written a few classes, but I've never encountered a class method (Well, a method which passes cls as a parameter). Could anybody show me some examples?

我已经使用并编写了一些类,但是我从来没有遇到过类方法(嗯,一个通过cls作为参数的方法)。谁能给我举几个例子吗?

Thanks!

谢谢!

1 个解决方案

#1


82  

Instance methods

When creating an instance method, the first parameter is always self. You can name it anything you want, but the meaning will always be the same, and you should use self since it's the naming convention. self is (usually) passed hiddenly when calling an instance method; it represents the instance calling the method.

创建实例方法时,第一个参数总是self。你可以给它取任何你想要的名字,但是它的含义总是一样的,你应该使用self,因为它是命名约定。self(通常)在调用实例方法时是隐藏传递的;它表示调用该方法的实例。

Here's an example of a class called Inst that has an instance method called introduce():

下面是一个名为Inst的类的例子,它有一个实例方法叫做introduction ():

class Inst:

    def __init__(self, name):
        self.name = name

    def introduce(self):
        print("Hello, I am %s, and my name is " %(self, self.name))

Now to call this method, we first need to create an instance of our class. Once we have an instance, we can call introduce() on it, and the instance will automatically be passed as self:

现在要调用这个方法,我们首先需要创建一个类的实例。一旦我们有了一个实例,我们可以在它上面调用引入(),实例将自动地作为self传递:

myinst = Inst("Test Instance")
otherinst = Inst("An other instance")
myinst.introduce()
# outputs: Hello, I am <Inst object at x>, and my name is Test Instance
otherinst.introduce()
# outputs: Hello, I am <Inst object at y>, and my name is An other instance

As you see, we're not passing the parameter self, it get's hiddenly passed with the period operator; we're calling Inst class's instance method introduce, with the parameter of myinst or otherinst. This means that we can call Inst.introduce(myinst) and get the exact same result.

正如你所看到的,我们没有传递参数self,它会随着周期运算符被隐藏起来;我们调用Inst类的实例方法,使用myinst或otherinst的参数。这意味着我们可以调用Inst.introduce(myinst)并得到完全相同的结果。


Class methods

The idea of class method is very similar to instance method, only difference being that instead of passing the instance hiddenly as a first parameter, we're now passing the class itself as a first parameter.

类方法的思想与实例方法非常相似,只是不同之处在于,我们现在将类本身作为第一个参数传递,而不是将实例作为第一个参数来传递。

class Cls:

    @classmethod
    def introduce(cls):
        print("Hello, I am %s!" %cls)

Since we're passing only a class to the method, no instance is involved. This means that we don't need an instance at all, we call the class method as if it was a static function:

因为我们只向方法传递一个类,所以不涉及实例。这意味着我们根本不需要实例,我们调用类方法就好像它是一个静态函数:

 Cls.introduce() # same as Cls.introduce(Cls)
 # outputs: Hello, I am <class 'Cls'>

Notice that again Cls is passed hiddenly, so we could also say Cls.introduce(Inst) and get output "Hello, I am <class 'Inst'>. This is particularly useful when we're inheriting a class from Cls:

注意,Cls也被间接地传递,所以我们也可以说Cls. introduction (Inst)并获得输出“Hello, I am 。这在继承Cls类时特别有用:

class SubCls(Cls):
    pass

SubCls.introduce()
# outputs: Hello, I am <class 'SubCls'>

#1


82  

Instance methods

When creating an instance method, the first parameter is always self. You can name it anything you want, but the meaning will always be the same, and you should use self since it's the naming convention. self is (usually) passed hiddenly when calling an instance method; it represents the instance calling the method.

创建实例方法时,第一个参数总是self。你可以给它取任何你想要的名字,但是它的含义总是一样的,你应该使用self,因为它是命名约定。self(通常)在调用实例方法时是隐藏传递的;它表示调用该方法的实例。

Here's an example of a class called Inst that has an instance method called introduce():

下面是一个名为Inst的类的例子,它有一个实例方法叫做introduction ():

class Inst:

    def __init__(self, name):
        self.name = name

    def introduce(self):
        print("Hello, I am %s, and my name is " %(self, self.name))

Now to call this method, we first need to create an instance of our class. Once we have an instance, we can call introduce() on it, and the instance will automatically be passed as self:

现在要调用这个方法,我们首先需要创建一个类的实例。一旦我们有了一个实例,我们可以在它上面调用引入(),实例将自动地作为self传递:

myinst = Inst("Test Instance")
otherinst = Inst("An other instance")
myinst.introduce()
# outputs: Hello, I am <Inst object at x>, and my name is Test Instance
otherinst.introduce()
# outputs: Hello, I am <Inst object at y>, and my name is An other instance

As you see, we're not passing the parameter self, it get's hiddenly passed with the period operator; we're calling Inst class's instance method introduce, with the parameter of myinst or otherinst. This means that we can call Inst.introduce(myinst) and get the exact same result.

正如你所看到的,我们没有传递参数self,它会随着周期运算符被隐藏起来;我们调用Inst类的实例方法,使用myinst或otherinst的参数。这意味着我们可以调用Inst.introduce(myinst)并得到完全相同的结果。


Class methods

The idea of class method is very similar to instance method, only difference being that instead of passing the instance hiddenly as a first parameter, we're now passing the class itself as a first parameter.

类方法的思想与实例方法非常相似,只是不同之处在于,我们现在将类本身作为第一个参数传递,而不是将实例作为第一个参数来传递。

class Cls:

    @classmethod
    def introduce(cls):
        print("Hello, I am %s!" %cls)

Since we're passing only a class to the method, no instance is involved. This means that we don't need an instance at all, we call the class method as if it was a static function:

因为我们只向方法传递一个类,所以不涉及实例。这意味着我们根本不需要实例,我们调用类方法就好像它是一个静态函数:

 Cls.introduce() # same as Cls.introduce(Cls)
 # outputs: Hello, I am <class 'Cls'>

Notice that again Cls is passed hiddenly, so we could also say Cls.introduce(Inst) and get output "Hello, I am <class 'Inst'>. This is particularly useful when we're inheriting a class from Cls:

注意,Cls也被间接地传递,所以我们也可以说Cls. introduction (Inst)并获得输出“Hello, I am 。这在继承Cls类时特别有用:

class SubCls(Cls):
    pass

SubCls.introduce()
# outputs: Hello, I am <class 'SubCls'>