python怎么区别同名窗口,Python:同名的常规方法和静态方法

Introduction

I have a Python class, which contains a number of methods. I want one of those methods to have a static counterpart—that is, a static method with the same name—which can handle more arguments. After some searching, I have found that I can use the @staticmethod decorator to create a static method.

Problem

For convenience, I have created a reduced test case which reproduces the issue:

class myclass:

@staticmethod

def foo():

return 'static method'

def foo(self):

return 'public method'

obj = myclass()

print(obj.foo())

print(myclass.foo())

I expect that the code above will print the following:

public method

static method

However, the code prints the following:

public method

Traceback (most recent call last):

File "sandbox.py", line 14, in

print(myclass.foo())

TypeError: foo() missing 1 required positional argument: 'self'

From this, I can only assume that calling myclass.foo() tries to call its non-static counterpart with no arguments (which won't work because non-static methods always accept the argument self). This behavior baffles me, because I expect any call to the static method to actually call the static method.

I've tested the issue in both Python 2.7 and 3.3, only to receive the same error.

Questions

Why does this happen, and what can I do to fix my code so it prints:

public method

static method

as I would expect?

解决方案

functions are looked up by name, so you are just redefining foo with an instance method. There is no such thing as an overloaded function in Python. You either write a new function with a separate name, or you provide the arguments in such a way that it can handle the logic for both.

In other words, you can't have a static version and an instance version of the same name. If you look at its vars you'll see one foo.

In [1]: class Test:

...: @staticmethod

...: def foo():

...: print 'static'

...: def foo(self):

...: print 'instance'

...:

In [2]: t = Test()

In [3]: t.foo()

instance

In [6]: vars(Test)

Out[6]: {'__doc__': None, '__module__': '__main__', 'foo': }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值