【问题标题】:What kind of method is this in Python? [duplicate]这在 Python 中是什么样的方法? [复制]
【发布时间】:2020-07-10 09:15:38
【问题描述】:

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

这个:

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

这里到底发生了什么?如果我不将self 传递给a() 方法,它是一个什么样的方法?为什么没有类的实例它也能工作?

【问题讨论】:

    标签: python


    【解决方案1】:

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

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

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

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

    x = newClass()
    x.print_b()
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-21
    • 2019-08-10
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2015-01-07
    • 2016-07-12
    • 2021-06-17
    相关资源
    最近更新 更多