其他分享
首页 > 其他分享> > @staticmethod的作用

@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

标签:person,eatting,human,night,print,eat,作用,staticmethod
来源: https://blog.csdn.net/zhou_438/article/details/118906598