Classes and Pointers

Classes

The following code creates a Cookie class.

class Cookie:
    def __init__(self, color):
        self.color = color

    def get_color(self):
        return self.color

    def set_color(self, color):
        self.color = color

cookie_one = Cookie('green')
cookie_two = Cookie('blue')

print('Cookie one is', cookie_one.get_color())
print('Cookie two is', cookie_two.get_color())

cookie_one.set_color('yellow')

print('\nCookie one is now', cookie_one.get_color())
print('Cookie two is still', cookie_two.get_color())

__init__ is a special method that is called when a new instance of a class is created. It is used to initialize the instance. __init__ is a constructor.

Pointers

The following piece of code is an example of not using a pointer.

In this case, updating num1 does not change num2.

The following is an example of using a pointer.

In this case, updating dict1 changes dict2. The reason is that dict1 and dict2 are pointing to the same object. The unused object will be garbage collected.

Last updated