Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

python - Python3: check if method is static

Simmilar question (related with Python2: Python: check if method is static)

Lets concider following class definition:

class A:
  def f(self):
    return 'this is f'

  @staticmethod
  def g():
    return 'this is g'

In Python 3 there is no instancemethod anymore, everything is function, so the answer related to Python 2 will not work anymore.

As I told, everything is function, so we can call A.f(0), but of course we cannot call A.f() (argument missmatch). But if we make an instance a=A() and we call a.f() Python passes to the function A.f the self as first argument. Calling a.g() prevents from sending it or captures the self - so there have to be a way to test if this is staticmethod or not.

So can we check in Python3 if a method was declared as static or not?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
class A:
  def f(self):
    return 'this is f'

  @staticmethod
  def g():
    return 'this is g'
print(type(A.__dict__['g']))
print(type(A.g))

<class 'staticmethod'>
<class 'function'>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...