【发布时间】:2016-07-07 15:17:21
【问题描述】:
我来自 .NET 和 Javascript 背景,我正在努力学习 Python(用于 Raspberry Pi)。
现在我正试图弄清楚 Python 中的 OOP 以及方法和类的使用。但是@staticmethod 有点问题
class Car(object):
"""description of class"""
def __init__(self, make, model):
self.make = make
self.model = model
@staticmethod
def makeFirstNoise():
print("Vrooooommm!")
def makeSecondNoise():
print("Mweeeeeeeeeh!")
这就是我实现我的类并尝试运行这两种方法的方式。
from Car import Car
mustang = Car('Ford', 'Mustang')
mustang.makeFirstNoise()
mustang.makeSecondNoise()
这是输出:
Vrooooommm!
Traceback (most recent call last):
File "D:\Dev\T\PythonHelloWorld\PythonHelloWorld\PythonHelloWorld.py", line 5, in <module>
mustang.makeSecondNoise()
TypeError: makeSecondNoise() takes 0 positional arguments but 1 was given
那么问题来了,为什么我不能在没有我的 staticmethod 属性的情况下执行第二种方法?如果我像这样直接返回文本,这似乎可行:
def makeSecondNoise():
return "Mweeeeeeeh!"
print(mustang.makeSecondNoise())
【问题讨论】:
标签: python python-3.x methods static-methods