Let's say you wanted to make a dog class. A dog class needs some attributes like size, color, name, and breed. That's where the __init__ method comes in to play. The __init__ method initializes, or gives values for, the attributes. When you write an __init__method, there is a parameter called self. That represents an instance of that class. You can predefine the attributes in the __init__ method or allow the caller to initialize them by values in the parameter list. Here is an example of the Dog Class:
Now, a plain dog that does nothing is pretty boring. The dog needs some action! This is where we write methods. Writing a method in a class is the same thing as writing a regular function but if you want the dog class to use that method, you would need to have the keyword self in the parameter list. Here is an example the dog class with a bark method.
Now, we have created a simple dog class with a method. We need to create an object of that class! To do this, you simply write Dog *object name* = new Dog(*arguments*) just like in the first example. To use the class's methods, We can say *object name*.*method name*(arguments) just like in the previous example. Although self is a parameter in the methods, we don't write an argument for it when we are calling the methods or creating a new class.
We can also change the attributes of a class outside of the class by saying *object name*.*attribute* = *value*. Here is an example:
Copyright © 2024 PieceOfAPie - All Rights Reserved.
Powered by GoDaddy
We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.