【问题标题】:Python List methodsPython 列表方法
【发布时间】:2016-01-16 16:47:09
【问题描述】:

我不得不在 Python 中进行文本处理。

于是我创建了一个类TextProcessing

manipulator = TextProcessing("one two three four four")
repr(manipulator) => "one two three four four"
manipulator["four"]  //=> [3, 4] => I made a list for that

但在那之后我不得不做一个这样的函数:

manipulator.two.replace("second") => "one second three four four"

我不知道如何将这两者与我的列表联系起来。

【问题讨论】:

    标签: python list function call


    【解决方案1】:

    你可以玩覆盖__getattr__

    class A(object):
        def __init__(self, s):
            self.s = s
        def replace(self, x):
            self.s = self.s.replace(self.x, x)
        def __getattr__(self, name):
            self.x = name
            return self
    
    a = A('abc')
    a.b.replace('X')
    print a.s
    

    class B(object):
        def __init__(self, x, y):
            self.x = x
            self.y = y
        def replace(self, x):
            self.x.s = self.x.s.replace(self.y, x)
    class A(object):
        def __init__(self, s):
            self.s = s
        def __getattr__(self, name):
            return B(self, name)
    
    a = A('abc')
    a.b.replace('X')
    print a.s
    

    【讨论】:

    • 感谢您的帮助
    • 我还有一个问题:如何使用 getattr 获取多个属性?
    • 恐怕没那么容易
    猜你喜欢
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 2020-11-17
    • 2018-04-26
    • 2020-01-24
    • 1970-01-01
    • 2010-10-08
    相关资源
    最近更新 更多