在 python 中多次调用类方法

Calling classmethod multiple times in python

我正在尝试创建一个可以被一次又一次调用的类方法,但是它只工作一次就停止了。这是代码:

class NewBytes(bytes):
    def __init__(self, var):
        self.var= var

    @classmethod
    def rip(cls):
        return cls(var[2:])

a = b"12asd5789"
x = NewBytes(a)

print(x, x.rip(), x.rip().rip(), x.rip().rip().rip())

这是我从中得到的:

b'12asd5789' b'asd5789' b'asd5789' b'asd5789'

然而,我想要的是:

b'12asd5789' b'asd5789' b'd5789' b'789'

提前致谢。

可能您实际上并不需要 class 方法,因为您需要在此处访问实例状态。

class NewBytes(bytes):
    def __init__(self, x):
        self.x = x

    def rip(self):
        return type(self)(self.x[2:])

我之前使用 self.x 的回答没有意义,因为这是一种 class 方法(回答太快了)。我认为这是 XY 问题的一个例子,请参见下面的示例,了解如何使用 class 方法。

class Test(object):
    x = "hey there whats up this is a long string"

    @classmethod
    def TestFunction(cls):
        cls.x = cls.x[3:]
        print(cls.x)


print(Test().x)
Test().TestFunction()
Test().TestFunction()
Test().TestFunction()
Test().TestFunction()
Test().TestFunction()