gpt4 book ai didi

Python静态方法,为什么?

转载 作者:太空狗 更新时间:2023-10-29 18:29:06 24 4
gpt4 key购买 nike

<分区>

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com