Python静态方法,为什么?

标签 python oop attributes static-methods class-method

<分区>

Possible Duplicate:
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 中也是一样的,我不知道。

最佳答案

你想用那个staticmethod实现什么?如果您不知道它的作用,您指望它如何解决您的问题?

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

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

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

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

关于Python静态方法,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10922700/

相关文章:

c# - 隐藏父类的实现细节

PHP : implementing states with objects

ios - NSLayoutAttributeLeft 与 NSLayoutAttributeLeading 的区别

python - 如何轮询/sys中的文件

java - java中的最大继承级别是多少?

c# - 有人得到了 C# MVC 的出生日期验证属性吗?

ruby-on-rails - 防止事件记录 INSERT 为 NULL?

python - 使用数据透视表正确整理数据 - 将索引保留为两级

python - 如何在 Windows (Python) 上安装 leveldb

python - fb预言家 : Predict a future holiday