为什么在这种方法中不使用`self`? [英] Why is `self` not used in this method?
问题描述
我的印象是 Python 类中的方法总是需要 self
参数(我知道它实际上不必是 self代码>,只是一些关键字).但是,我写的这个类不需要它:
I was under the impression that methods within Python classes always require the self
argument (I know that it doesn't actually have to be self
, just some keyword). But, this class that I wrote doesn't require it:
import ZipFile
import os
class Zipper:
def make_archive(dir_to_zip):
zf = zipfile.ZipFile(dir_to_zip + '.zip', 'w')
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()
看到了吗?没有self
.当我在 make_archive
中包含一个 self
参数时,我得到一个 TypeError: make_archive() missing one positional argument
错误.为了弄清楚为什么会发生这种情况,我实际上是从文档中复制并尝试运行一个类似的程序:
See? No self
. When I include a self
argument to make_archive
, I get a TypeError: make_archive() missing one positional argument
error. In my search to figure out why this is happening, I actually copied and tried to run a similar program from the docs:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
print(MyClass.f()) # I added this statement to have a call line
我得到了同样的错误!
TypeError: f() missing 1 required positional argument: 'self'
在包含 Zipper()
类的同一个模块中,我有多个类都使用了 self
.我不明白这里的理论,这使得很难知道什么时候做什么,特别是因为程序直接从文档中复制 (这是文档页面) 在我运行时失败.我在 Debian Linux 上使用 Python 3.5 和 3.4.我唯一能想到的是它是一个静态方法(如果您在 @staticmethod
上面包含 @staticmethod
,上面写的 Zipper.make_archive()
>make_archive 方法),但我找不到一个很好的解释来确定.
In the same module that contains the Zipper()
class, I have multiple classes that all make use of self
. I don't understand the theory here, which makes it difficult to know when to do what, especially since a program copied directly from the docs (this is the docs page) failed when I ran it. I'm using Python 3.5 and 3.4 on Debian Linux. The only thing that I can think of is that it's a static method (and the Zipper.make_archive()
as written above works fine if you include @staticmethod
above the make_archive
method), but I can't find a good explanation to be sure.
推荐答案
您正试图将其用作静态方法.在你的例子中;
You are trying to use it as a static method. In your example;
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
a = MyClass()
a.f() # This should work.
调用 MyClass.f()
假定 f
对于 MyClass
是静态的.您可以将其设为静态:
Calling MyClass.f()
assumes f
is static for MyClass
. You can make it static as:
class MyClass:
@staticmethod
def f(): # No self here
return 'hello world'
MyClass.f()
这篇关于为什么在这种方法中不使用`self`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!