0

I'm very new to python I apologize if this is a stupid question but so far I haven't been able to google it successfully.

I'm making a class called Cookie and it has methods that return the number of cookies created and also resets them. What I am having issues with is in the tests it calls the classes methods on the actual class and not an object created from the class. IE:

instead of:

c = Cookie()
c.count()

they use in the tests:

Cookie.count()

when count is a method in the cookie class but cookie is not an object. So far I have not had success calling methods on the class that they are in, just on objects created by the class. I've always thought of classes as templates to create objects. Can anyone explain this? Thank you.

What I Have

Tests

Leah Denham
  • 271
  • 3
  • 8

2 Answers2

1

This code keeps a counter on the class object and increments it each time the class is instantiated. Class methods get a reference to the class object so they can find num_cookies. They are also callable through the self object in class instances, so you can get to them multiple ways.

class Cookie:

    num_cookies = 0

    @classmethod
    def count(cls):
        return cls.num_cookies

    @classmethod
    def add_cookie(cls):
        cls.num_cookies += 1

    def __init__(self):
        self.add_cookie()

print(Cookie.count())
print(Cookie().count())
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

Ok, after taking a look at the code, which I will past here:

class Cookie(object):
    global count
    count = 0

    def __init__(self, count = 0):
        self.count = count
        self.count += 1

    def count():
        print(count)

    def reset_counter():
        count = 0
        return count

You have a number of problems.

One, you're declaring count as a global variable, inside the body of the class object.

Further along, you have a function called count.

This is going to lead to some serious problems.

Watch:

In [8]: Cookie
Out[8]: __main__.Cookie

In [9]: count
Out[9]: <function __main__.count>

In [10]: 

I think what you want to go for is keep track of how often an object is instantiated.

To achieve that, you don't need the global, it will just confuse things.

In [18]: class Cookie(object):
    ...:     counter = 0
    ...: 
    ...:     def __init__(self):
    ...:         Cookie.counter += 1
    ...: 
    ...:     @classmethod
    ...:     def count(cls):
    ...:         print(Cookie.counter)

    ...:     @classmethod
    ...:     def reset_counter(cls):
    ...:         Cookie.counter = 0
    ...:         return Cookie.counter
    ...:     

In [19]: c=Cookie()

In [20]: Cookie.count()
1

In [21]: c=Cookie()

In [22]: Cookie.count()
2

You also need to be a bit more careful about naming of variables colliding with other things in the same namespace (such as count vs counter in my example)

James R
  • 4,571
  • 3
  • 30
  • 45