关于类中的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()
输出:
^{pr2}$
例二: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
我知道我不能打电话给任何人自我属性在staticmethods中,我只是不太确定何时以及为什么要使用它。在我看来,如果您创建一个具有几个属性的类,也许您希望以后使用它们,而不是拥有一个所有属性都不可调用的staticmethod。
有人能解释一下吗?Python是我的第一种编程语言,所以如果在Java中也是这样,我不知道。在