Python class

Use classes to define new objects in Python

In addition to using the types provided by Python, we can also declare our own classes and instantiate objects from the classes.

Objects are instances of classes. Class is the type of object.

Define a class in this way:

class <class_name>:
    # my class

For example, let us define a Dog class

class Dog:
    # the Dog class

A class can define methods:

class Dog:
    # the Dog class
    def bark(self):
        print('WOF!')

selfThe method parameter points to the current object instance, and this parameter must be specified when the method is defined.

We create an instance of the class,purpose, Use the following syntax:

roger = Dog()

right nowrogerIs a new object of type Dog.

If you run

print(type(roger))

You will get<class '__main__.Dog'>

A special method__init__()Called a constructor, when we create a new object from this class, we can use it to initialize one or more properties:

class Dog:
    # the Dog class
    def __init__(self, name, age):
        self.name = name
        self.age = age
<span style="color:#66d9ef">def</span> <span style="color:#a6e22e">bark</span>(self):
    <span style="color:#66d9ef">print</span>(<span style="color:#e6db74">'WOF!'</span>)</code></pre></div>

We use it in this way:

roger = Dog('Roger', 8)
print(roger.name) # 'Roger'
print(roger.age)  # 8

roger.bark() # ‘WOF!’

One important features of classes is inheritance.

We can create an Animal class with a method walk():

class Animal:
    def walk(self):
        print('Walking..')

and the Dog class can inherit from Animal:

class Dog(Animal):
    def bark(self):
        print('WOF!')

Now creating a new object of class Dog will have the walk() method as that’s inherited from Animal:

roger = Dog()
roger.walk() # 'Walking..'
roger.bark() # 'WOF!'

More python tutorials: