python - 这在 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
这里究竟发生了什么?如果我不传递self
给a()
方法,它是一个什么样的方法?为什么它在没有类的实例的情况下工作?
解决方案
这是一种静态方法。它可以工作,但无法访问该类具有的任何其他属性/方法。例如,假设您有以下课程。
class newClass:
b = 9
def print_b():
print(b)
newClass.print_b()
这将引发错误,因为函数无法访问变量 b。希望这可以帮助。
同样,您不能执行以下操作,因为当您调用这样的方法时,您会自动将类的实例传递给函数。因此,该函数将抛出一个错误,说它需要 0 个位置参数,但您已经传递了一个。
x = newClass()
x.print_b()
推荐阅读
- c++ - Taglib 从任意文件 c++ 中读取 ID3v2 标签
- android - setSystemUiVisibility 和 View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 已弃用 在 Stack 或 Google 中找不到示例
- visual-studio - 是什么导致 Visual Studio 键盘快捷键更改?(VS2019)
- python - 为什么求和列表理解比生成器表达式更快?
- python - 如果所有变量都需要在其中包含浮点数(十进制),那么在 python 中处理变量名的最佳方法是什么?
- javascript - React 无法从 Node APII 获取数据
- html - 使用 html 将下拉列表放在搜索栏中
- python - 打开用户交互式 GUI 的 Slack 应用程序
- python - File uploads using flask looking in CWD for file to upload instead of using users sample directory
- python - 如何删除 .xml 文件的匹配子元素属性?