Class in python

 



In Python, a class is a blueprint or template for creating objects, which are instances of the class. A class defines a set of attributes and methods that the objects of the class can have.


Here is an example of a simple Python class:


```python

class Car:

    # class variable

    wheels = 4

    

    # constructor method

    def __init__(self, make, model, year):

        self.make = make

        self.model = model

        self.year = year

    

    # instance method

    def drive(self):

        print(f"{self.make} {self.model} is driving...")

```


In the example above, the `Car` class has a class variable `wheels` which is set to 4. The class also has a constructor method `__init__` which initializes the instance variables `make`, `model`, and `year` with the values passed as arguments. The class also has an instance method `drive` which prints a message indicating that the car is driving.


To create an object of the `Car` class, you can call the constructor method:


```python

my_car = Car("Toyota", "Camry", 2021)

```


You can access the attributes of the object using the dot notation:


```python

print(my_car.make)  # output: Toyota

print(my_car.year)  # output: 2021

```


You can also call the methods of the object using the dot notation:


```python

my_car.drive()  # output: Toyota Camry is driving...

```

Comments

Popular posts from this blog

About Mohit Kumar Tyagi

Internet Programming Lab-BCA 506P