Everything in Python is just like an object. A class comprises methods and attributes or properties.
In the following example, we have created a class named Car.
The __init__ method is the first method that is called during the creation of an object.
In the __init__ method, we can set the default values of the attributes namely carname and year. The first argument in the methods of a class is “self”. This points to the current object.
Every class by default has __init__ and __str__ methods. The __str__ method returns the string representation of the class.
We have defined a method called calc.
We can instantiate the object of the class by passing the attributes as parameters to the class name. In our example, we have provided “Audi” and 2022 as the parameters.
class Car:
def __init__(self, carname, year):
self.carname = carname
self.year = year
def calc(self, mileage):
return 10 * mileage
def __str__(self):
return f"{self.carname} - {self.year}"
c1 = Car("Audi", 2022)
print(c1)
print(c1.calc(200))
The link to the Github repository is here .