如果要直接使用self而不是class对象,python函数是否需要self

Ayu*_*wal -2 python python-3.x

我有下面的类和其中定义的功能。

class utils:
    def pass_hash(unhashed):
        hashed = hashlib.sha256(unhashed)
        hashed = hashed.hexdigest()
        return hashed
Run Code Online (Sandbox Code Playgroud)

当我打电话

print(utils.pass_hash('abc'.encode()))
Run Code Online (Sandbox Code Playgroud)

它工作正常,但如果我打电话

obj = utils()
print(obj.pass_hash('abc'.encode()))
Run Code Online (Sandbox Code Playgroud)

它给出以下错误:

  print(obj.pass_hash('abc'.encode()))
TypeError: pass_hash() takes 1 positional argument but 2 were given
Run Code Online (Sandbox Code Playgroud)

而如果我在函数中传递自变量,则这种行为会逆转,即它可以很好地与对象配合使用,但是在访问时像utils.pass_hash()一样会给出错误。

有人可以解释一下这种行为吗?

glg*_*lgl 5

这是类及其实例的通常行为。

如果这样做obj = utils(),您将创建该类的实例utils(最好将其命名为Utils)。如果您执行实例方法调用,例如obj.pass_hash(x)obj则会自动将其作为第一个参数传递给该方法,并x作为第二个参数传递。因此,要求将该方法定义为def pass_hash(self, x)

如果要在类本身上调用方法,则必须使用@staticmethod或对其进行注释@classmethod

@staticmethod只要self抑制了A 的自动通过,A 就会更改所描述的行为。A @classmethod具有使用类对象调用的方法。