docyoda
docyoda

Reputation: 131

Call a class with append that targets class variable

For example:

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

How can I call Foo().append() that appends to Foo().bar?

Ex:

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'

Is this possible?

Upvotes: 2

Views: 53

Answers (2)

Jab
Jab

Reputation: 27485

You could set self.append in the __init__ function:

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

Then call it as expected:

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

Although why not just subclass list if this is the goal?

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"]

Upvotes: 0

docyoda
docyoda

Reputation: 131

I added an append function myself:

# ... in the Foo() class

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

Edit: A simpler method that would also work

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

(Thank you @RaySteam)

Upvotes: 1

Related Questions