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

2024-10-03 00:31:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我来自.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())

Tags: 方法selfmakenetmodeldefcarclass
2条回答

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

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

在此之后,您可以调用您的方法没有任何问题

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

在Java中,this(表示实例对象)被隐式地传递给方法—这是造成混淆的原因

makeSecondNoise导致错误的原因是它自动传递了一个参数self,因为它没有声明为staticmethodself是调用函数的类的实例。这最终导致了错误,因为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参数的自动传递有关

相关问题 更多 >