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.

num1 = 11
num2 = num1

print("Before value is updated:")
print("num1:", num1)
print("num2:", num2)

num1 = 22
print("\nAfter value is updated:")
print("num1:", num1)
print("num2:", num2)

In this case, updating num1 does not change num2.

The following is an example of using a pointer.

dict1 = {'a': 1, 'b': 2}
dict2 = dict1

print("Before value is updated:")
print("dict1:", dict1)
print("dict2:", dict2)

dict1['a'] = 3
print("\nAfter value is updated:")
print("dict1:", dict1)
print("dict2:", dict2)

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