|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 fc5igm 于 2021-6-14 19:53 编辑
- class CodeA:
- @staticmethod
- def foo():
- print("调用静态方法 foo()")
复制代码- class CodeB:
- @classmethod
- def foo(cls):
- print("调用类方法 foo()")
复制代码
上面小甲鱼给的答案代码,但是敲编辑器里却报错了。请问这个题的答案应该怎么写?
classmethod 修饰过后,print_hello() 就变成了类方法,可以直接通过 Hello.print_hello() 调用,而无需绑定实例对象了。
哪怕缩进正确,可以运行了,但是输入foo也还是无法调用。无法复现甲鱼宣称的功能
- >>> class Test:
- def test(self):
- pass
-
- >>> Test.foo
- Traceback (most recent call last):
- File "<pyshell#45>", line 1, in <module>
- Test.foo
- AttributeError: type object 'Test' has no attribute 'foo'
- >>> Test.foo()
- Traceback (most recent call last):
- File "<pyshell#46>", line 1, in <module>
- Test.foo()
- AttributeError: type object 'Test' has no attribute 'foo'
复制代码
@staticmethod缩进搞错了
- class CodeA:
- @staticmethod
- def foo():
- print("调用静态方法 foo()")
复制代码
|
|