【问题标题】:Is it possible to run a print() inside a method without the @staticmethod attribute?是否可以在没有 @staticmethod 属性的方法内运行 print() ?
【发布时间】: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


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      【解决方案2】:

      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 参数的自动传递有关。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-13
        • 2012-08-23
        • 2011-03-18
        相关资源
        最近更新 更多