是否可以在没有@staticmethod 属性的方法中运行 print()?

Is it possible to run a print() inside a method without the @staticmethod attribute?

我有 .NET 和 Javascript 背景,我正在努力学习 Python(针对 Raspberry Pi)。
现在我正试图弄清楚 Python 中的 OOP 以及方法和 classes 的使用。但是@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!")

这就是我实现 class 并尝试 运行 这两种方法的方式。

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属性我不能执行第二个方法?如果我直接像这样 return 文本,这似乎有效:

def makeSecondNoise():
    return "Mweeeeeeeh!"

print(mustang.makeSecondNoise())

makeSecondNoise 导致错误的原因是因为它自动传递了一个参数 self,因为它没有声明为 staticmethodself 是调用该函数的 class 的实例。这最终导致了错误,因为 makeSecondNoise 没有被编码为接受任何参数;就像这样做:

def something():
    ...
something("Foo")

以下是 self 工作原理的示例:

>>> class Car:
...     def makenoise(self):
...         print(self)
...
>>> mustang = Car()
>>> mustang.makenoise()
<__main__.Car object at 0x0000000005498B38> # We can see that "self" is a reference to "mustang"

您的问题与 print 无关(如果没有 print 我也无法让您的示例工作)- 它与 self 参数的自动传递有关.

在 Python 中,所有方法调用(除了类方法和静态方法)显式传递对象实例作为第一个参数。约定是将此参数命名为self。此显式参数应包含在方法签名中:

class Car(object):
    def makeSecondNoise(self):  # note that method takes one argument
        print("Mweeeeeeeeeh!")

之后您可以毫无问题地调用您的方法。

mustang = Car('Ford', 'Mustang')
mustang.makeSecondNoise()

在 Java 中,this(表示实例对象)隐式传递给方法 - 这是您混淆的根源。