首页 > 解决方案 > 这在 Python 中是什么样的方法?

问题描述

我正在阅读有关实例、静态和类方法的信息,并发现了以下内容。

这个:

class A:
    def a(self, num):
            print("A.a(): ", num)

    @staticmethod
    def aa(num):
            print("A.aa(): ", num)

完全按预期工作:

>>> A.a(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a() missing 1 required positional argument: 'num'
# I understand that this happens since `a()` is an instance method

>>> A.aa(1)
A.aa():  1

>>> A().a(1)
A.a():  1

但是,如果我修改以从其参数A.a()中删除,即:self

class A:
    def a(num):
            print("A.a(): ", num)

    @staticmethod
    def aa(num):
            print("A.aa(): ", num)

有时候是这样的:

>>> A.a(1)
A.a():  1
# I don't understand why this works

>>> A.aa(1)
A.aa():  1

>>> A().a(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a() takes 1 positional argument but 2 were given
# I understand that this happens because the first argument
# being given to `a()` is the instance of A

这里究竟发生了什么?如果我不传递selfa()方法,它是一个什么样的方法?为什么它在没有类的实例的情况下工作?

标签: python

解决方案


这是一种静态方法。它可以工作,但无法访问该类具有的任何其他属性/方法。例如,假设您有以下课程。

class newClass:
b = 9
def print_b():
    print(b)
    
newClass.print_b()

这将引发错误,因为函数无法访问变量 b。希望这可以帮助。

同样,您不能执行以下操作,因为当您调用这样的方法时,您会自动将类的实例传递给函数。因此,该函数将抛出一个错误,说它需要 0 个位置参数,但您已经传递了一个。

x = newClass()
x.print_b()

推荐阅读