preloader

Python101: 10. Classes and Objects

post thumb
Python
by Admin/ on 08 Jul 2021

Python101: 10. Classes and Objects


If you’ve ever learned about object-oriented thinking, you know that object-oriented thinking consists of two basic concepts: classes and objects, and let’s learn more about Python classes and objects.


1 Basic concepts


1.1 Object-Orientation

Object-oriented is an abstraction, a way of looking at things in a categorical way, in Java programming terms: everything is an object; object-oriented has three main features: encapsulation, inheritance, and polymorphism.

1.2 Classes

As mentioned above, object-oriented is a way to see the problem in a categorical way, a category is a class, you can see the class as an abstract template, such as: Car class.

1.3 Objects

An object is an instance created from a class.

2 Basic usage

2.1 Definition of classes

### Class definition
class Car:
    pass

2.2 Object creation

### Create an instance object of Car c
class Car:
    pass
	
c = Car()

2.3 Defining properties in a class

### Define the attributes of the Car class name
class Car:
    name = 'BMW'

3 Methods in the class


3.1 Built-in Methods

When Python creates any class, it will contain some built-in methods, mainly including the following.

methods description
__init__ Constructor, called when an object is created
__del__ destructor, used when releasing the object
__repr__ print, convert
__setitem__ Assign a value by index
__getitem__ Get the value by index
__len__ get length
__cmp__ compare operations
__call__ function call
__add__ addition
__sub__ subtraction
__mul__ multiplication
__div__ divide
__mod__ the remainder operation
__pow__ multiplication

3.2 Custom Methods

Python has three common methods: instance methods, class methods, and static methods, all of which are defined in classes.

3.2.1 Class Methods

A class method is a method that operates on the class itself as an object.

Definition and Usage

'''
Class methods (adjustable class variables, callable by instances, callable by classes)
1. class methods are implemented through the @classmethod decorator and can only access class variables, not instance variables.
2、Pass the current class object through the cls parameter, no instantiation required.
'''

class Car(object):
    name = 'BMW'
    def __init__(self, name):
        self.name = name
    @classmethod
    def run(cls,speed):
        print(cls.name,speed,'driving')
# Access method 1
c = Car("BMW")
c.run("100mph")
# Access method 2
Car.run("100mph")
3.2.2 Static methods

Static methods are functions in a class that do not require an instance.

Definition and use

'''
Static methods (adjustable class variables, callable by instance, callable by class)
1. a method without a self argument decorated with @staticmethod.
2. static methods are nominally managed by the class, but in practice they cannot access any properties of the class or the instance in the static method.
3, the call does not need to pass the class or instance.
'''
class Car(object):
    name = 'BMW'
    def __init__(self, name):
        self.name = name
    @staticmethod
    def run(speed):
        print(Car.name,speed,'driving')
		
# Access method 1
c = Car("BMW")
c.run("100mph")
# Access method 2
Car.run("100mph")
3.2.3 Instance methods

Instance methods are the methods that can be used by instances of a class.

Definition and use

# Instance methods (adjustable class variables, adjustable instance variables, callable by instances)
# The first argument is forced to be the instance object self.
class Car(object):
    name = 'BMW'
    def __init__(self, name):
        self.name = name
    def run(self, speed):
        print(self.name,speed,'driving')

# Access
c = Car("BMW")
c.run("100 mph")

4 Class inheritance

Definition and use

# Basic syntax: class ClassName(BaseClassName)
# Parent class
class Car(object):
    name = 'BMW'
    def __init__(self, name):
        self.name = name
    def run(self,speed):
        print(self.name,speed,'driving')
        
# Subclasses
class BMWCar(Car):
    conf = "Affordable"
    pass

# Call the run method of the parent class Car
bc = BMWCar("BMW Affordable Car")
bc.run("100mph")

5 Polymorphism of classes

Definition and use

# Parent class
class Car(object):
    name = 'BMW'
    def __init__(self, name):
        self.name = name
    def run(self,speed):
        print('Car-->',self.name,speed,'driving')

# Subclass 1
class BMWCar(Car):
    def run(self,speed):
        print('BMWCar-->',self.name,speed,'driving')

# Subclass 2
class SVWCar(Car):
    def run(self,speed):
        print('SVWCar-->',self.name,speed,'driving')

# Call the run method
c = Car("Car")
c.run("120mph")

bc = BMWCar("BMW")
bc.run("100mph")

sc = SVWCar("Volkswagen")
sc.run("80 mph")

# Output results
'''
Car--> Car 120 mph Run
BMWCar--> BMW 100 mph Driving
SVWCar--> Volkswagen 80mph driving
'''

In the above example, we can see that: c, bc and sc are different types of objects, but when they call the run method, they all call the methods of their respective classes, which is polymorphism.

Summary


This section has introduced you to the definition and use of Python classes and objects, and has provided Python engineers with the support to use different types of methods in their projects as they see fit.


Reference.

https://www.readwithu.com/Article/python9/Preface.html https://github.com/JustDoPython/python-100-day/tree/master/day-010

comments powered by Disqus