我有几个关于类中的静态方法的问题。我将从举一个例子开始。
示例一:
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 中是一样的,我不知道。