I159
I159

Reputation: 31109

Python class methods overloading

How can I overload class methods? I failed with:

class D(object):
    def create(self):
        foo = 100
        bar = 'squirrels'
        baz = 'I have %d insane %s in my head.' % (foo, bar)
        return baz     

class C(D):
    def create(self):
        super(C, self).create()
        baz = 'I have %s cute %s in my yard.' % (self.foo, self.bar)

C().create()

Traceback was:

AttributeError: 'C' object has no attribute 'foo'

Upvotes: 1

Views: 1185

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409166

In D.create you do not set the variables on self, which means the variable foo is a local variable of that function.

class D(object):
    def create(self):
        self.foo = 100
        self.bar = 'squirrels'
        self.baz = 'I have %d insane %s in my head.' % (self.foo, self.bar)
        return self.baz

Upvotes: 0

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

You have tried to use local variables as class attributes. Try to do the following changes:

class D(object):
    def create(self):
        self.foo = 100
        self.bar = 'squirrels'
        baz = 'I have %d insane %s in my head.' % (self.foo, self.bar)
        return baz

class C(D):
    def create(self):
        super(C, self).create()
        print self.foo
        self.baz = 'I have %s cute %s in my yard.' % (self.foo, self.bar)

C().create()

Upvotes: 3

Related Questions