When we create a class we are essentially creating our own data type. To do this we must first come up with a name for our class and populate it with some methods.
The name of this class is "Dog" and currently it has two methods: __init__ and speak.
Typically when we create a class we create a method that is known as a constructor. A constructor is what will be called automatically when we create a new instance of that class. To create a constructor we must use the method name __init__(). We do not need to call this method by doing something like "instance.__init__()" because when we first create a Dog object it will be automatically called.
To create a new instance of our Dog class we can do the following:
The Self Keyword
You may have noticed that each of my methods above contain the keyword self as a parameter. For now all of the methods we make must do just this. When we call methods on an instance of the class the name of that instance is automatically passed to the method as the argument self. This allows us to access and change attributes that are specific to this instance.
To create a new attribute we must use the self keyword in the following way.
Since the __init__ methods now takes two arguments (self and name) we must pass a name when we create a new Dog object.
Since this name is specific to each instance when we create multiple Dog objects they all may have different names.
Now that we know how to create attributes it's time to talk about accessing and changing them. We can change attributes in two ways. It is best practice to change an attribute within the class like so.
The second way to change attribute is to do so outside of the class, like so:
Note: We can add new attributes to a class from outside of the __init__ method. However, we must do this within another method in the class. (Watch video if confused)