【发布时间】: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类似于 javasstatic。@staticmethod几乎没用。 -
谢谢乔希,也许我没有正确搜索,感谢链接,现在会检查
标签: python oop attributes static-methods class-method