使用append调用以variab类为目标的类

2024-04-29 04:25:16 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

class Foo:
    def __init__(self):
        self.bar = ["baz", "qux", "quux", "quuz", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud"]

如何调用附加到Foo().barFoo().append()

例如:

x = Foo()

x.append("asd")

# What I want to happen:
# self.bar now is [..., "asd"]

# What actually happens:
# AttributeError: 'Foo' object has no attribute 'append'

这可能吗


Tags: selffooinitdefbarbazwhatclass
2条回答

我自己添加了一个append函数:

# ... in the Foo() class

    def append(self, value):
        return self.bar.append(value)

编辑:一个更简单的方法,也可以工作

# ... in Foo().__init__(self)
    self.append = self.bar.append

(感谢@RaySteam)

您可以在__init__函数中设置self.append

class Foo:
    def __init__(self):
        self.bar = ["baz", "qux", "quux", "quuz", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud"]
        self.append = self.bar.append

然后按预期调用:

x = Foo()
x.append("asd")
print(x.bar)
#[..., "asd"]

如果这是我们的目标,为什么不只是子类list

class Foo(list):
    def __init__(self):
        self.extend(["baz", "qux", "quux", "quuz", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud"])

f = Foo()
f.append('asd')
print(f)
#[..., "asd"]

相关问题 更多 >