11 python oop attributes static-methods class-method
我在课堂上有一些关于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()
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
示例二:
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.
Run Code Online (Sandbox Code Playgroud)
输出
Hello Ephexeve M, your age is 18
Run Code Online (Sandbox Code Playgroud)
我看到我无法在static方法中调用任何self.attribute,我只是不确定何时以及为何使用它.在我看来,如果你创建一个带有一些属性的类,也许你想稍后使用它们,而不是一个静态方法,其中所有属性都不可调用.有谁能解释我这个?Python是我的第一个编程langunge,所以如果在Java中这是相同的,我不知道.
Ben*_*Ben 11
你想用它做staticmethod什么?如果你不知道它的作用,你是如何期望它解决你的问题?
或者你只是在玩耍,看看有什么用staticmethod?在这种情况下,阅读文档以告知它的作用可能会更有成效,而不是随机应用它并试图从行为中猜测它的作用.
在任何情况下,应用于类@staticmethod中的函数定义都会产生"静态方法".不幸的是,"静态"是编程中最容易混淆的术语之一; 这意味着该方法不依赖于或改变对象的状态.如果我foo在类中定义了静态方法Bar,那么无论属性包含什么,调用bar.foo(...)(类的bar某个实例Bar)将完全相同bar.事实上,我可以直接从课堂上调用它,因为Bar.foo(...)我甚至没有实例!
这是通过简单地不将实例传递给静态方法来实现的,因此静态方法没有self参数.
静态方法很少是必需的,但偶尔也很方便.它们与在类外定义的简单函数非常相似,但是将它们放在类中会将它们标记为与类"关联".您通常使用它们来计算或处理与类密切相关的事物,但实际上并不是对某个特定对象的操作.
| 归档时间: |
|
| 查看次数: |
4001 次 |
| 最近记录: |