@staticmethod的作用

class human():
    @staticmethod
    def eat(x):
        print('person a eatting %s in night' %x)
    print(2)
    
human.eat('香蕉')
human().eat('西瓜')

class human: 
    def eat(x):
        print('person a eatting %s in night' %x)
    print(2)
human.eat('香蕉')
human().eat()
human().eat('西瓜')

运行结果:

2
person a eatting 香蕉 in night
person a eatting 西瓜 in night
2
person a eatting 香蕉 in night
person a eatting <__main__.human object at 0x000001D1489556A0> in night
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15080/4175715165.py in <module>
     14 human.eat('香蕉')
     15 human().eat()
---> 16 human().eat('西瓜')

TypeError: eat() takes 1 positional argument but 2 were given

上一篇:Python中@staticmethod和@classmethod的作用和区别


下一篇:【DTM】HUAWEI Ads与DTM网页转化追踪(一)