繁体   English   中英

为什么在这种方法中没有使用`self`?

[英]Why is `self` not used in this method?

我的印象是Python类中的方法总是需要self参数(我知道它实际上不必是self ,只是一些关键字)。 但是,我写的这个类不需要它:

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错误。 在我的搜索中找出为什么会发生这种情况,我实际上复制并试图从文档中运行类似的程序:

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。 我唯一能想到的是它是一个静态方法(如果你在make_archive方法之上包含@staticmethod上面写的Zipper.make_archive()工作正常),但我找不到一个好的解释来确定。

您正尝试将其用作静态方法。 在你的例子中;

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是静态的。 您可以将其设为静态:

class MyClass:
    @staticmethod
    def f():  # No self here
       return 'hello world'

MyClass.f()

self的事情是隐含地添加它。 也就是说,调用代码表示Myclass().f() ,但被调用者看到Myclass().f(self) 它还暗示从Myclass某个实例调用该方法,该实例放在self变量中。 关键是方法可能以某种方式使用和/或修改实例数据(否则它们为什么会在该类中?)并且自动提供有问题的实例是很方便的。

如果你不需要实例数据,你应该使用@staticmethod如果它实际上更像是一个函数而不是object方法,或者@classmethod如果该方法是要继承的,并且可能由不同的类使用不同。 请参阅@ pankaj-daga的回答,了解staticmethods的一些介绍。

Foo.bar()语法也被import Foo而不是from Foo import bar import Foo的函数使用,这也是混淆的可能来源。 为了您的目的,这是完全不同的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM