【发布时间】: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