在python中多次调用classmethod

时间:2018-08-20 21:45:43

标签: python-3.x class-method

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

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'

谢谢。

2 个答案:

答案 0 :(得分:0)

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

08-20 21:29:25.848 26010-26010/com.swimlabs.pcms.progressionapp 
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.swimlabs.pcms.progressionapp, PID: 26010
java.lang.NullPointerException: Attempt to invoke virtual method 'void 
com.swimlabs.pcms.progressionapp.MyAdapter.filterList(java.util.ArrayList)' 
on a null object reference
    at 
 com.swimlabs.pcms.progressionapp.CoachActivity.filter
(CoachActivity.java:75)
    at 
com.swimlabs.pcms.progressionapp.CoachActivity.access$000
(CoachActivity.java:28)
    at com.swimlabs.pcms.progressionapp.CoachActivity$1.afterTextChanged
(CoachActivity.java:60)
    at android.widget.TextView.sendAfterTextChanged(TextView.java:9770)
    at 
android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:12522)
    at 

android.text.SpannableStringBuilder.sendAfterTextChanged
(SpannableStringBuilder. 
java:1273)
    at 
android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:576)

答案 1 :(得分:0)

我以前使用self.x的答案没有任何意义,因为这是一个类方法(答案太快了)。我认为这是XY问题的一种情况,请参见以下有关如何使用类方法的示例。

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()