python建立類和類方法

月瘋發表於2021-12-20

建立一個類的三種方法: 

class Annimao():
    pass
class Annimao(object):
    pass
class Annimao:
    pass

三種類方法:

1、例項方法

class Person:
    def __init__(self,age,name):
        self.age = age
        self.name = name
    def speak(self):
        print('說了一段話')

if __name__ == '__main__':

    per = Person(24,'huitao')
    Person.speak()
    per.speak()
Person.speak()不允許類名字呼叫例項方法
F:\開發工具\pythonProject\flaskTest\venv\Scripts\python.exe F:/開發工具/pythonProject/flaskTest/tessss.py
Traceback (most recent call last):
  File "F:\開發工具\pythonProject\flaskTest\tessss.py", line 79, in <module>
    Person.speak()
TypeError: speak() missing 1 required positional argument: 'self'

Process finished with exit code 1

 去掉Person.speak()

結果:

F:\開發工具\pythonProject\flaskTest\venv\Scripts\python.exe F:/開發工具/pythonProject/flaskTest/tessss.py
說了一段話

Process finished with exit code 0

2、類方法

class Employer(object):
    def __init__(self):
        pass
    @classmethod
    def speak(cls):
        print('不允許講話')

if __name__ == '__main__':

    em = Employer()
    em.speak()
    Employer.speak()

結果:輸出了同樣的內容

F:\開發工具\pythonProject\flaskTest\venv\Scripts\python.exe F:/開發工具/pythonProject/flaskTest/tessss.py
不允許講話
不允許講話

Process finished with exit code 0

3、靜態方法

class Gun():
    def __init__(self):
        pass
    @staticmethod
    def speak():
        print('又開始說話了')

if __name__ == '__main__':
    g = Gun()
    Gun.speak()
    g.speak()

結果:輸出同樣內容

F:\開發工具\pythonProject\flaskTest\venv\Scripts\python.exe F:/開發工具/pythonProject/flaskTest/tessss.py
又開始說話了
又開始說話了

Process finished with exit code 0

註釋:不推薦使用類方法和靜態方法,建議使用例項方法

相關文章