我来自.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中,所有方法调用(除了classmethods和staticmethods)都显式地传递对象实例作为第一个参数。约定将此参数命名为
self
。此显式参数应包含在方法签名中:在此之后,您可以调用您的方法没有任何问题
在Java中,
this
(表示实例对象)被隐式地传递给方法—这是造成混淆的原因makeSecondNoise
导致错误的原因是它自动传递了一个参数self
,因为它没有声明为staticmethod
self
是调用函数的类的实例。这最终导致了错误,因为makeSecondNoise
没有编码为接受任何参数;就像这样:以下是
self
工作原理的示例:你的问题与
print
无关(没有print
我也无法得到你的例子)-它与self
参数的自动传递有关相关问题 更多 >
编程相关推荐