Create a method attribute in a class

Viewed 3657

I can create a function of the following format.

def bar():
    if not hasattr(bar, 'c'):
        bar.c = 0
    bar.c += 1
    return bar.c

When run it produces the following output, as intended:

>>> bar()
1
>>> bar()
2
>>> bar()
3

But if I suddenly move this function to a class, Python gives me an error.

class Foo(object):

    def bar(self):
        if not hasattr(self.bar, 'c'):
            self.bar.c = 0
        self.bar.c += 1
        return self.bar.c

Now I get

>>> foo = Foo()
>>> foo.bar()
...
AttributeError: 'method' object has no attribute 'c'

It's telling me it has no attribute, but I'm trying to create the attribute. What's going on here?

1 Answers
Related