【问题标题】:Python Static methods, why? [duplicate]Python 静态方法,为什么? [复制]
【发布时间】:2012-06-10 23:16:18
【问题描述】:

可能重复:
What is the difference between @staticmethod and @classmethod in Python?

我有几个关于类中的静态方法的问题。我先举个例子。

示例一:

class Static:
    def __init__(self, first, last):
        self.first = first
        self.last = last
        self.age = randint(0, 50)
    def printName(self):
        return self.first + self.last
    @staticmethod
    def printInfo():
        return "Hello %s, your age is %s" % (self.first + self.last, self.age)

x = Static("Ephexeve", "M").printInfo()

输出:

Traceback (most recent call last):
  File "/home/ephexeve/Workspace/Tests/classestest.py", line 90, in <module>
    x = Static("Ephexeve", "M").printInfo()
  File "/home/ephexeve/Workspace/Tests/classestest.py", line 88, in printInfo
    return "Hello %s, your age is %s" % (self.first + self.last, self.age)
NameError: global name 'self' is not defined

示例二:

class Static:
    def __init__(self, first, last):
        self.first = first
        self.last = last
        self.age = randint(0, 50)
    def printName(self):
        return self.first + self.last
    @staticmethod
    def printInfo(first, last, age = randint(0, 50)):
        print "Hello %s, your age is %s" % (first + last, age)
        return

x = Static("Ephexeve", "M")
x.printInfo("Ephexeve", " M") # Looks the same, but the function is different.

输出

Hello Ephexeve M, your age is 18

我知道我不能在静态方法中调用任何 self.attribute,我只是不确定何时以及为什么使用它。在我看来,如果您创建一个带有一些属性的类,也许您想稍后使用它们,并且没有一个所有属性都不可调用的静态方法。 任何人都可以向我解释这个吗? Python 是我的第一个编程语言,所以如果这在 Java 中是一样的,我不知道。

【问题讨论】:

  • 讨厌投票结束,但我链接到的问题的答案非常好。请注意,@classmethod 类似于 javas static@staticmethod 几乎没用。
  • 谢谢乔希,也许我没有正确搜索,感谢链接,现在会检查

标签: python oop attributes static-methods class-method


【解决方案1】:

你想用staticmethod 实现什么目标?如果您不知道它的作用,您希望它如何解决您的任何问题?

或者你只是想看看staticmethod 做了什么?在这种情况下,告诉read the docs 可能会更有效率,而不是随机应用它并试图从行为中猜测它的作用。

在任何情况下,将@staticmethod 应用于类中的函数定义会产生“静态方法”。不幸的是,“静态”是编程中最容易混淆的重载术语之一。这意味着该方法不依赖或改变对象的状态。如果我在类Bar 中定义了一个静态方法foo,那么无论bar 是什么,调用bar.foo(...)(其中bar 是类Bar 的某个实例)都会做同样的事情s 属性包含。事实上,当我什至没有实例时,我可以直接从类中调用它为Bar.foo(...)

这是通过简单地不将实例传递给静态方法来实现的,因此静态方法没有self 参数。

静态方法很少需要,但偶尔会很方便。它们实际上与在类外部定义的简单函数相同,但是将它们放在类中会将它们标记为与类“关联”。您通常会使用它们来计算或执行与类密切相关的事情,但实际上并不是对某个特定对象的操作。

【讨论】:

    猜你喜欢
    • 2021-04-10
    • 2014-09-28
    • 2011-04-03
    • 2012-12-28
    • 1970-01-01
    • 2011-11-16
    • 2020-07-02
    • 2015-01-19
    • 2015-10-15
    相关资源
    最近更新 更多