gpt4 book ai didi

python - 为什么在没有 "self"且没有装饰器的情况下声明的 Python 类的方法不会引发异常?

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:33 25 4
gpt4 key购买 nike

我认为以下代码会导致错误,因为据我所知,Python 类中的方法必须将“self”(或任何其他标签,但按照惯例为“self”)作为其第一个如果使用了 @classmethod 装饰器,则为“cls”或类似参数,如果使用了 @staticmethod 装饰器,则为无。

即使 test_method 不满足这些要求,为什么我在终端中使用 Python 3.5 运行时没有出现错误?它作为静态方法似乎工作正常,但没有装饰器。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

class MyClass:

def test_method(args):
print(args[1])

@staticmethod
def static_method():
print("static_method")

@classmethod
def class_method(cls):
print("class_method")


def main(args):
MyClass.test_method(args)


if __name__ == '__main__':
sys.exit(main(sys.argv))

输出:

$ python3 testscript.py "testing"
$ testing

编辑:

我的问题也可以用不同的措辞来表达,将注意力从 self 转移到 @staticmethod:“我怎么会得到一个没有 @ 的看似有效的静态方法?静态方法装饰器?”

最佳答案

在 Python 2 中,类主体中定义的函数会自动转换为“未绑定(bind)方法”,如果没有 staticmethod 装饰器则无法直接调用。在 Python 3 中,这个概念被移除了; MyClass.text_method 是一个位于 MyClass 命名空间内的简单函数,可以直接调用。

在 Python 3 中仍然使用 staticmethod 的主要原因是如果您还想在实例 上调用该方法。如果不使用装饰器,该方法将始终将实例作为第一个参数传递,从而导致 TypeError。

关于python - 为什么在没有 "self"且没有装饰器的情况下声明的 Python 类的方法不会引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52831534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com