Dog class

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

# Allows new objects of type Dog to be instantiated
class Dog:

    # constructor
    def __init__(self, name):
        self.name = name    # attribute of a dog
        self.tricks = []    # attribute of a dog

    # function that can be called on a dog
    def add_trick(self, trick):
        self.tricks.append(trick)


d = Dog('Bandit')
e = Dog('Max')

d.add_trick('roll over')
e.add_trick('play dead')

print("Bandit knows:", d.tricks)
print("Max knows:", e.tricks)

Counter class

# Allows new objects of type Counter to be instantiated
class Counter:
    
    # constructor with an optional argument (if not specified, start is 0 by default)
    def __init__(self, start=0):
        self.val = start    # attribute
    
    def increment(self):
        self.val += 1
    
    def decrement(self):
        self.val -= 1
    
# Creates a new counter with 0 as initial value by default
c = Counter()
print("Current value: ", c.val)

# Increment the counter 5 times
for i in range(5):
    c.increment()
print("Current value: ", c.val)

# Creates a new counter with 200 as the initial value
d = Counter(200)
print("Value of other counter d: ", d.val)

# Decrements the counter 5 times
for i in range(5):
    d.decrement()
print("Value of other counter d: ", d.val)