Python Daily 29: Create a Simple Dog Class 🐶
Tags: python, beginners, daily, classes
Published: 2024-01-04 08:11:58

These days I am in the process of understanding classes. 

The last two days I did this Banking System exercise where I had `class Bank` and `class Account` and people could deposit and withdraw money etc.

I was able to make this work but I used way too much ChatGPT and still don’t feel comfortable about the basics, so today I asked ChatGPT for a really simple exercise on classes. 

Next is what I got, and you can find my solution below

# **Exercise: Create a Simple `Dog` Class**

**Objective:**

- Understand the basic structure of a Python class.
- Learn how to create an instance (object) of a class.
- Get familiar with the concept of methods and attributes.

**Task Description:**

1. **Define a Class:**
    - Create a class named **`Dog`**.
    - The class should have an **`__init__`** method (constructor) that takes two parameters: **`name`** and **`age`**.
2. **Add Attributes:**
    - Inside the **`__init__`** method, assign these parameters to instance attributes called **`name`** and **`age`**.
3. **Create an Instance Method:**
    - Add a method named **`bark`** to the **`Dog`** class.
    - This method doesn't take any parameters besides **`self`**.
    - When called, it should print a string: **`"Woof! My name is [name]!"`**, where **`[name]`** is the name of the dog.
4. **Create an Instance of the Dog Class:**
    - Outside the class, create an instance of **`Dog`**. For example, **`my_dog = Dog("Rex", 5)`**.
    - Print out the name and age of **`my_dog`** using the attributes.
    - Call the **`bark`** method on your **`my_dog`** instance.
    

# My Code

Ok this is perhaps as simple as it gets with classes:

```python
class Dog: # This is the class
    ...

def main():
    dog = Dog # This is an object (as in object-oriented programming)
    dog.name = "Sausage"
    dog.age = 1
    print(f'my dog is called {dog.name} and is {dog.age} years old')

if __name__ == '__main__':
    main()
```

Next I tried a different way to create the dog object, but this results in an error: `TypeError: Dog() takes no arguments`

```python

# This Code doesn't work

class Dog: 
    ...

def main():
    name = "Sausage"
    age = 1
    dog = Dog(name, age)
    print(f'my dog is called {dog.name} and is {dog.age} years old')

if __name__ == '__main__':
    main()
```

Next I added the `__init__` method, which nicely makes my code work again

```python
class Dog: 
    def __init__(self, name, age):
        self.name = name
        self.age = age

def main():
    name = "Sausage"
    age = 1
    dog = Dog(name, age)
    print(f'my dog is called {dog.name} and is {dog.age} years old')

if __name__ == '__main__':
    main()
```

I can still add more attributes that I didn’t define in `__init__`

```python
class Dog: 
    def __init__(self, name, age):
        self.name = name
        self.age = age

def main():
    name = "Sausage"
    age = 1
    dog = Dog(name, age)
    dog.friend = "Mike"
    print(f'my dog is called {dog.name} and is {dog.age} years old. His friend is {dog.friend}')

if __name__ == '__main__':
    main()
```

Next I tried to get my dog to bank. The code from my first attempt actually doesn’t do anything, not even create an error

```python
# This Code doesn't work

class Dog: 
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark():
        print(f'Woof! My name is {name}!')

def main():
    name = "Sausage"
    age = 1
    dog = Dog(name, age)
    dog.bark

if __name__ == '__main__':
    main()
```

Ok turns out I need to call the method with `dog.barg()` just like a function. Also had to add ‘self’ to the method to make it work with the name.

```python
class Dog: 
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print(f'Woof! My name is {self.name}!')

def main():
    name = 'Sausage'
    age = 1
    dog = Dog(name, age)
    dog.bark()

if __name__ == '__main__':
    main()
```

Alright that’s it! And now I can create as many dogs as I want and have them bark.

```python
class Dog: 
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print(f'Woof! My name is {self.name}!')

def main():
    name1 = 'Sausage'
    age1 = 1
    dog1 = Dog(name1, age1)

    name2 = 'Rex'
    age2 = 5
    dog2 = Dog(name2, age2)

    dog1.bark() 
    dog2.bark()

if __name__ == '__main__':
    main()
```

Wow you might think that was way too simple, but it was exactly what I had to get more comfortable with, so very happy with this small dog exercise today. I didn’t use any ChatGPT for help here, but rewatched parts of [CS50 Python Week 8](https://cs50.harvard.edu/python/2022/weeks/8/) on OOP