首页 文章

Python静态方法,为什么? [重复]

提问于
浏览
10

可能重复:Python中@staticmethod和@classmethod有什么区别?

我在课堂上有一些关于staticmethods的问题 . 我将首先举一个例子 .

示例一:

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

我看到我无法在static方法中调用任何self.attribute,我只是不确定何时以及为何使用它 . 在我看来,如果你创建一个带有一些属性的类,也许你想稍后使用它们,而不是一个静态方法,其中所有属性都不可调用 . 有谁能解释我这个? Python是我的第一个编程langunge,所以如果在Java中这是相同的,我不知道 .

1 回答

  • 10

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

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

    无论如何,将 @staticmethod 应用于类中的函数定义会产生"static method" . 不幸的是,"Static"是编程中最容易混淆的术语之一;这意味着该方法不依赖于或改变对象的状态 . 如果我在类 Bar 中定义了一个静态方法 foo ,那么无论 bar 的属性包含什么,调用 bar.foo(...) (其中 bar 是类 Bar 的某个实例)将完全相同 . 事实上,当我甚至没有实例时,我可以直接从类中调用它作为 Bar.foo(...)

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

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

相关问题