python object oriented programming

How does Xiaobai become a python data analyst

Day 15 ----- > Object Oriented Programming

Are you single? The next time you meet someone who asks this question, you can directly answer him. Everyone has an object, because everything is an object.

Our previous programming is instruction programming, that is, the input instructions are executed one by one. There is no problem when the program is simple, but with the increase of the complexity of the problem, instruction programming will obviously not better support us to solve the problem. In order to better solve complex problems, we use object-oriented programming.

"A program is a collection of instructions". When a program is run, the statements in the program will become one or more instructions, Then by the CPU (central processing unit) to execute. In order to simplify the program design, we use functions, put relatively independent and frequently reused code into functions, and call functions when they need to be used. If the function of a function is too complex and bloated, we can further split the function into multiple sub functions to reduce the complexity of the system Miscellaneous.

programming paradigm: it is the methodology of programming and the programmer's cognition and understanding of the program. Nowadays, the popular programming paradigms mainly include object-oriented programming and functional programming.

Object oriented definition

In order to solve the "software crisis", people have introduced the programming paradigm of "Object-Oriented Programming". In object-oriented programming, the data in the program and the function of operating data are a logical whole. We call it object. Objects can receive messages. The way to solve the problem is to create objects and send various messages to objects; Through message passing, multiple objects in the program can work together, so that complex systems can be constructed and real problems can be solved.

Object oriented programming: a group of data and data processing methods are composed of objects, objects with the same behavior are summarized into classes, the internal details of objects are hidden by encapsulation, the specialization and generalization of classes are realized by inheritance, and the dynamic dispatch based on object types is realized by polymorphism.

Class:

An abstract concept obtained by extracting the common features of objects with common features (static features and dynamic features).

Simply put, a class is the blueprint (template) of an object. Only with a class can we create this type of object.

Object:

Object: an object is an entity that can receive messages. Object-oriented programming is to solve problems by sending messages to objects. Object is a concrete concept.

Object = data + function (method) - > object logically turns data and the function of operating data into a whole.

Properties of objects: ~ everything is an object Objects have properties and behaviors Each object is unique The object must belong to a class

object-oriented programming

Three big steps:

  1. Define class - > class naming uses hump naming method (capitalize the first letter of each word) Data abstraction: find static features (attributes) related to objects - > find nouns Behavior abstraction: find dynamic features (Methods) related to objects - > find verbs
  2. Create object

  3. Send a message

Define class

In Python, you can use the class keyword plus the class name to define the class. By indentation, we can determine the code block of the class, just like defining a function. In the code block of a class, we need to write some functions. We said that a class is an abstract concept, so these functions are our extraction of the common dynamic features of a class of objects. The functions written in classes are usually called methods. Methods are the behavior of objects, that is, the messages that objects can receive. The first parameter of the method is usually self, which represents the object itself that receives the message.

Data abstraction (properties): find the properties of this class

Behavior abstraction (method): find what this class can do.

# Step 1: define class
class Student:
    """student"""

    # Data abstraction (properties)
    def __init__(self, name, age):
        # Initialization method
        self.name = name
        self.age = age

    # Behavior abstraction (method)
    def eat(self):
        """having dinner"""
        print(f'{self.name}I am eating.')

    def study(self, course_name):
        """study"""
        print(f'{self.name}I am learning{course_name}.')

    def play(self, game_name):
        """play"""
        print(f'{self.name}Playing{game_name}.')

    def watch_tv(self):
        """Watch tv"""
        print(f'{self.name}Watching Island movies.')

Note: the hump method is used when defining the class - > the first letter of the class name is capitalized.

create object

After we define a class, we can use constructor syntax to create objects,

# Step 2: create object -- > constructor syntax -- > class name (...,...)
stu1 = Student('Zhang San', 26)
stu2 = Student('Li Si', 31)

The so-called constructor syntax is followed by parentheses on the name of the class. The above code creates two student objects, one assigned to the variable stu1 and the other assigned to the variable stu2.

Send a message (call the method of the object)
# Call the method through "class. Method". The first parameter is the object receiving the message, and the second parameter is the name of the course studied
Student.study(stu1, 'Python Programming')    # Zhang San is learning Python programming
# Call the method through "object. Method". The object in front of the point is the object receiving the message. Only the second parameter needs to be passed in
stu1.study('Python Programming')             # Zhang San is learning Python programming

Student.play(stu2)    # Li Si is playing a game
stu2.play()           # Li Si is playing a game
Initialization method

If we want to define properties for the Student object, we can modify the Student class and add a class named__ init__ Methods. When we call the constructor of Student class to create an object, we will first obtain the memory space required to save the Student object in memory, and then execute it automatically__ init__ Method to initialize the memory, that is, put the data into the memory space.

We can add__ init__ Method to specify the attribute for the Student object and assign the initial value to the attribute at the same time__ init__ Methods are also commonly referred to as initialization methods.

# Define class
class Student:
    """student"""

    def __init__(self, name, age):
        """Initialization method"""
        self.name = name
        self.age = age

    def study(self, course_name):
        """study"""
        print(f'{self.name}I am learning{course_name}.')

    def play(self):
        """play"""
        print(f'{self.name}Playing games.')
# create object
# Because the initialization method has two parameters besides self
# Therefore, these two parameters should be passed in when calling the constructor of Student class to create an object
stu1 = Student('Zhang San', 40)
stu2 = Student('Li Si', 15)

# Send a message
stu1.study('Python Programming')    # Zhang San is learning Python programming
stu2.play()                    # Li Si is playing a game

Magic method (magic method)

We pass__ init__ Method binds properties and gives initial values to the object when it is created. In Python, use two underscores__ (read "dunder") )The method of beginning and ending is usually a method with special purpose and meaning. We generally call it magic method or magic method. If we don't want to see the address of the object when printing the object, but see our customized information, we can place it in the class__ repr__ Magic method. The string returned by this method is the content that will be displayed when printing the object with the print function.

class Student:
    """student"""

    def __init__(self, name, age):
        """Initialization method"""
        self.name = name
        self.age = age

    def study(self, course_name):
        """study"""
        print(f'{self.name}I am learning{course_name}.')

    def play(self):
        """play"""
        print(f'{self.name}Playing games.')
    
    def __repr__(self):
        return f'{self.name}: {self.age}'


stu1 = Student('Zhang San', 25)
print(stu1)        # Zhang San: 25
students = [stu1, Student('Li Si', 16), Student('Wang Wu', 25)]
print(students)    # [Zhang San: 25, Li Si: 16, Wang Wu: 25]

Object oriented pillar

Three pillars of object-oriented programming: encapsulation: logically assemble data and functions that manipulate data into a whole (object).
- > hide the implementation details and expose the simple calling interface. inheritance: extend the existing class, create a new class, and reuse the code of the existing class. polymorphism: send the same message to different objects, and different objects perform different behaviors.

The fourth pillar: Abstraction: extracting commonalities (defining classes is an abstraction process, which requires data abstraction and behavior abstraction).

Encapsulation:

Hide all the implementation details that can be hidden, and only expose the simple calling interface to the outside world. The object method defined in the class is actually a kind of encapsulation, which allows us to execute the code in the method by sending a message to the object after creating the object, That is, we only know the name and parameters of the method (the external view of the method) and do not know the internal implementation details of the method (the internal view of the method).

Inheritance:

Object oriented programming language supports the creation of new classes based on existing classes, so as to reduce the writing of repeated code. The classes that provide inheritance information are called parent classes (superclasses and base classes), and the classes that get inheritance information are called subclasses (derived classes, derived classes) for example, when we define a student class and a teacher class, we will find that they have a large number of duplicate codes, and these duplicate codes are the public attributes and behaviors of teachers and students as human beings. Therefore, in this case, we should first define human beings, and then derive teacher classes and student classes from human beings through inheritance. The codes are as follows.

class Person:
    """human beings"""

    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def eat(self):
        print(f'{self.name}I am eating.')
    
    def sleep(self):
        print(f'{self.name}be sleeping.')


class Student(Person):
    """Student class"""
    
    def __init__(self, name, age):
        # super(Student, self).__init__(name, age)
        super().__init__(name, age)
    
    def study(self, course_name):
        print(f'{self.name}I am learning{course_name}.')


class Teacher(Person):
    """Teacher class"""

    def __init__(self, name, age, title):
        # super(Teacher, self).__init__(name, age)
        super().__init__(name, age)
        self.title = title
    
    def teach(self, course_name):
        print(f'{self.name}{self.title}Teaching{course_name}.')



stu1 = Student('Jinkra', 21)
stu2 = Student('Chu Duo', 22)
teacher = Teacher('Tao cost', 35, 'associate professor')
stu1.eat()
stu2.sleep()
teacher.teach('Python Programming')
stu1.study('Python Programming')

The inheritance syntax is to specify the parent class of the current class in parentheses after the class name when defining the class. If a class is defined without specifying its parent class, the default parent class is the object class. The object class is the top-level class in Python, which means that all classes are subclasses of it, either directly or indirectly. Python language allows multiple inheritance, that is, a class can have one or more parent classes. We will discuss the problem of multiple inheritance in more detail later. In the initialization method of subclasses, we can use super()__ init__ () to call the parent class initialization method. The super function is specially designed in Python built-in functions to obtain the parent class object of the current object. As can be seen from the above code, in addition to inheriting the properties and methods provided by the parent class, the child class can also define its own unique properties and methods, so the child class has more capabilities than the parent class. In actual development, we often replace a parent object with a subclass object, which is a common behavior in object-oriented programming, also known as the "Liskov Substitution Principle".

Polymorphism:

After the subclass inherits the method of the parent class, it can also rewrite the method (re implement the method). Different subclasses can give different implementation versions of the same method of the parent class. Such methods will show polymorphic behavior when the program runs (calling the same method and doing different things). Polymorphism is the most essential part of object-oriented programming,

The relationship between the two classes!

"""
example01 - Relationship between two classes!

~ is-a Relationships: Inheritance ---> Derived from one class to another, you can inherit multiple classes, but you can't inherit casually. The code is error prone. After inheritance
    a student is a person.
    a teacher is a person.
~ has-a Relationships: associations ---> Take an object of one class as an attribute of an object of another class
    a person has an identity card.
    a car has an engine.
    - ((normal) Association
    - Strong association: whole and part Association, aggregation and synthesis
~ use-a Relationships: dependencies ---> An object of one class is used as a parameter to a method of another class
 Or return value((used)
    a person use a vehicle.


Author: Data analysis elder martial brother
Date: 2021/8/6
"""



class Vehicle:
    """vehicle"""
    pass


class Horse(Vehicle):
    """horse"""
    pass


class Motobike(Vehicle):
    """motorcycle"""

    def __init__(self):
        self.engine = Engine()


class Engine:
    """engine"""
    pass


class Follower:
    """apprentice"""
    pass


class MrTang:
    """Tang Monk"""

    def __init__(self):
        """Relationship, apprentice"""
        self.followers = []

    def drive(self, vehicle):  # "" "dependencies,"""""
        """drive"""
        pass

Dynamic properties

Python is a dynamic language, "a language whose structure can be changed at runtime. For example, new functions, objects and even code can be introduced, existing functions can be deleted or other structural changes. The dynamic language is very flexible. At present, the popular Python and JavaScript are dynamic languages.

In Python, we can dynamically add attributes to objects, which is a privilege of Python as a dynamically typed language,

class Student:

    def __init__(self, name, age):
        self.name = name
        self.age = age


stu = Student('aged', 84461)
# Dynamically add sex attribute for Student object
stu.sex = 'male'

Static methods and class methods

Object methods (instance methods): all the methods defined in the class are object methods. In other words, these methods are messages that the object can receive. Messages sent to the object of the class.

Static methods and class methods: these two types of methods are messages sent to classes. In the object-oriented world, everything is an object. Each class we define is actually an object, and static methods and class methods are messages sent to class objects.

class Triangle(object):
    """Triangle class"""

    def __init__(self, a, b, c):
        """Initialization method"""
        self.a = a
        self.b = b
        self.c = c

    @staticmethod
    def is_valid(a, b, c):
        """Judge whether the length of three sides can form a triangle(Static method)"""
        return a + b > c and b + c > a and a + c > b

    # @classmethod
    # def is_valid(cls, a, b, c):
    #     "" "judge whether three sides can form a triangle (class method)" ""
    #     return a + b > c and b + c > a and a + c > b

    def perimeter(self):
        """Calculated perimeter"""
        return self.a + self.b + self.c

    def area(self):
        """Calculated area"""
        p = self.perimeter() / 2
        return (p * (p - self.a) * (p - self.b) * (p - self.c)) ** 0.5

Summary:

Programming paradigms such as instruction programming and functional programming. Because the real world is composed of objects, and objects are entities that can receive messages, object-oriented programming is more in line with human normal thinking habits.

Classes are abstract and objects are concrete. With classes, objects can be created and messages can be received. This is the basis of object-oriented programming.

The process of defining a class is an abstract process. Finding the public attributes of an object belongs to data abstraction, and finding the public methods of an object belongs to behavior abstraction.

Python objects can dynamically add attributes.

In the object-oriented world, everything is an object, and the class we define is also an object, so the class can also receive messages, and the corresponding method is class method or static method.

Through inheritance, we can create new classes from existing classes and reuse the existing class code.

Examples

1. Build a circular swimming pool. The outer ring is a corridor with a width of 3 meters. The corridor is 58.5 yuan per square meter, and the outermost wall is 38.5 yuan per meter. Ask for the cost of corridor and enclosure.

"""
example03 - Solving practical problems with object-oriented programming
 Build a circular swimming pool, the outer ring is a 3-meter-wide corridor, which is 58 per square meter.5 Yuan. The outermost wall is 38 yuan per meter.5 Yuan. Ask for the cost of corridor and enclosure.

init ---> initialize ---> initialization

Author: Xiaobai on the road
Date: 2021/8/5
"""
import math


class Circle:
    """circular"""

    def __init__(self, radius):
        """compare"""
        self.radius = radius

    def perimeter(self):
        """Perimeter"""
        return 2 * math.pi * self.radius

    def area(self):
        """m the measure of area"""
        return math.pi * self.radius ** 2


if __name__ == '__main__':
    r = float(input('Please enter the radius of the swimming pool: '))
    c1, c2 = Circle(r), Circle(r + 3)

    fence_price = c2.perimeter() * 38.5
    aisle_price = (c2.area() - c1.area()) * 58.5

    print(f'Cost of enclosure: {fence_price:.2f}element')
    print(f'Cost of aisle: {aisle_price:.2f}element')
    print(f'total: {fence_price + aisle_price: .2f}element')

2. Define a class to describe the digital clock.

"""Defines a class that describes a digital clock."""
import time


# Define digital clock class
class Clock(object):
    """Digital clock"""

    def __init__(self, hour=0, minute=0, second=0):
        """Initialization method
        :param hour: Time
        :param minute: branch
        :param second: second
        """
        self.hour = hour
        self.min = minute
        self.sec = second

    def run(self):
        """be in luck"""
        self.sec += 1
        if self.sec == 60:
            self.sec = 0
            self.min += 1
            if self.min == 60:
                self.min = 0
                self.hour += 1
                if self.hour == 24:
                    self.hour = 0

    def show(self):
        """Display time"""
        return f'{self.hour:0>2d}:{self.min:0>2d}:{self.sec:0>2d}'


# Create clock object
clock = Clock(23, 59, 58)
while True:
    # Send message to clock object to read time
    print(clock.show())
    # Sleep for 1 second
    time.sleep(1)
    # Send a message to the clock object to make it walk
    clock.run()

count down

"""
homework02 - 
Define a class to describe the countdown

Author: Data analysis elder martial brother
Date: 2021/8/5
"""
import time


class Time:

    # Data sampling
    def __init__(self, *, hour=24, minute=60, second=60):
        """
        Countdown clock
        :param hour: Time
        :param minute: branch
        :param second: second
        """
        self.hour = hour
        self.minute = minute
        self.second = second

    # Behavioral sampling
    def run(self):
        """be in luck"""
        self.second -= 1
        if self.second == -1:
            self.second += 60
            self.minute -= 1
            if self.minute == -1:
                self.minute += 60
                self.hour -= 1
        return self.hour == 0 and self.second == 0 and self.minute == 0

    def show(self):
        """Display time"""
        return f'{self.hour:0>2d}:{self.minute:0>2d}:' \
               f'{self.second:0>2d}'


# create object
if __name__ == '__main__':
    clock = Time(hour=0, minute=2, second=1)
    while True:
        print(clock.show())
        # Sleep for 1 second
        time.sleep(0.1)
        if clock.run():
            print('End of time')
            break

3. Define a class to describe a point on the plane. It is required to provide a method to calculate the distance to another point.

class Point(object):
    """Point on screen"""

    def __init__(self, x=0, y=0):
        """Initialization method
        :param x: Abscissa
        :param y: Ordinate
        """
        self.x, self.y = x, y

    def distance_to(self, other):
        """Calculate the distance from another point
        :param other: Another point
        """
        dx = self.x - other.x
        dy = self.y - other.y
        return (dx * dx + dy * dy) ** 0.5

    def __str__(self):
        return f'({self.x}, {self.y})'


p1 = Point(3, 5)
p2 = Point(6, 9)
print(p1, p2)
print(p1.distance_to(p2))

4. Poker game.

Our poker has only 52 cards (no king or King). The game needs to issue 52 cards to four players. Each player has 13 cards, which are arranged from small to large according to the order and points of spades, hearts, flowers and squares. Other functions are not realized for the time being.

"""
example06 - Write a poker game,
-brand
  -Attributes: decor, number of points
  -Behaviors: displaying
-poker
  -Properties: save a list of cards
  -Behavior: shuffle and deal cards
-game player
  -Attribute: name, save card in player's hand
  -Behavior: touching, sorting and playing cards


Author: Data analysis elder martial brother
Date: 2021/8/5
"""


class Card:
    """Decor"""

    def __init__(self, suite, face):
        self.suite = suite
        self.face = face


    def __str__(self):
        return self.show()

    def __repr__(self):
        return self.show()

    def __lt__(self, other):
        return self.face < other.suites

    def show(self):
        """

        :rtype: object
        """
        suites = {'S': '♠', 'H': '♥', 'D': '♣', 'C': '♦'}
        faces = ['A', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', ]
        # Get the corresponding characters according to the color and number of cards
        return f'{suites[self.suite]}{faces[self.face]}'


if __name__ == '__main__':
    card1 = Card('H', 9)
    card2 = Card('C', 6)
    card3 = Card('S', 13)
    print(card1, card2, card3)
    print(card1)
    # Identity operation card1 is card2
    print(card1 is card2)

"""
example07 - poker
-poker
  -Properties: save a list of cards
  -Behavior: shuffle and deal cards
Author: Data analysis elder martial brother
Date: 2021/8/6
"""
import random

from example06 import Card


class Poker:
    """poker"""

    def __init__(self):
        self.cards = []
        for suite in 'SHCD':
            for face in range(0, 14):
                self.cards = [Card(suite, face)]
        # Licensing position
        self.counter = 0

    def shuffle(self):
        """shuffle the cards"""
        self.counter = 0
        random.shuffle(self.cards)

    def deal(self):
        """Licensing"""
        card = self.cards[self.counter]
        self.counter += 1
        return card

    def has_mor(self):
        """Judge whether there are still cards"""
        return self.counter < len(self.cards)


def main():
    poker = Poker
    poker.shuffle()
    poker.deal()


if __name__ == '__main__':
    main()

"""
example08 - game player
-game player
  -Attribute: name, save card in player's hand
  -Behavior: touching, sorting and playing cards

Author: Data analysis elder martial brother
Date: 2021/8/6
"""
from example07 import Poker


class Player:
    """game player"""

    def __init__(self, nickname):
        """

        :param nickname: nickname
        """
        self.nickname = nickname
        self.cards = []

    def get_one_card(self, card):
        """Touch a card"""
        self.cards.append(card)

    def arrange(self):
        """Tidy up your cards"""
        self.cards.sort()

    def show(self):
        """Display player's cards"""
        print(self.nickname, end='')
        for card in self.cards:
            print(card, end='')
        print()


def main():
    poker = Poker()
    poker.shuffle()
    players = [Player('East evil'), Player('Western poison'), Player('South Emperor'), Player('Northern beggar')]
    for _ in range(13):
        for player in players:
            player.get_one_card(poker.deal())
    for player in players:
        player.arrange()
        print(f'{player.show()}: ', end='')
        print(player.cards)


if __name__ == '__main__':
    main()

5. Salary (monthly salary) settlement system

"""
example02 - Salary (monthly salary) settlement system

Three types of employees:
~ Department Manager: fixed monthly salary, 15000 yuan
~ Programmer: Hourly settlement monthly salary, 200 yuan per hour
~ Salesperson: base salary+Commission, base salary 1800 yuan, sales 5%Commission

--Method Rewriting: the subclass gives its own implementation version to the existing methods of the parent class,
--Polymorphism: send the same message to different objects, and different objects perform different behaviors.

Four pillars of object orientation:
1.Abstraction: extracting commonalities (defining classes),
2.encapsulation:Logically assemble data and functions that manipulate data into a whole (object).
**Hide all the implementation details that can be hidden, and only expose the simple calling interface to the outside world**. 
3.Inheritance: extend existing classes, create new classes, and reuse existing classes.
4.Polymorphism: send the same message to different objects, and different objects perform different behaviors.
Author: Data analysis elder martial brother
Date: 2021/8/6
"""
from abc import ABCMeta, abstractmethod


class Employee(metaclass=ABCMeta):
    """staff"""

    def __init__(self, name):
        self.name = name
        # self.on = on  # Job number

    @abstractmethod  # The declaration is not implemented and is left to subclass override.
    def get_salary(self):
        """Settle monthly salary"""
        pass


class Manager(Employee):
    """division manager"""

    def get_salary(self):
        return 15000.0


class Programmer(Employee):
    """programmer"""

    def __init__(self, name, working_hour=0):
        super().__init__(name)
        self.working_hour = working_hour

    # Method rewrite
    def get_salary(self):
        return 200 * self.working_hour


class Salesman(Employee):
    """salesperson"""

    def __init__(self, name, sales=0):
        super().__init__(name)
        self.sales = sales

    def get_salary(self):
        return 1800 + self.sales * 0.05


def main():
    # mg = Manager('wrong person ')
    # pg = Programmer('zhang San ', 200)
    # slm = Salesman('li Xinyi ', 5000)
    # Print (the salary of F '{mg. Name} is {mg.get_salary()}')
    # Print (the salary of F '{pg.name} is {pg.get_salary()}')
    # Print (the salary of F '{SLM. Name} is {slm.get_salary()}')
    emps = [
        Manager('Zhang San'), Programmer('Li Si'),
        Salesman('Wang Wu')
    ]
    for emp in emps:
        if type(emp) == Programmer:
            emp.working_hour = int(input(f'Please enter{emp.name}working hours:'))
        elif type(emp) == Salesman:
            emp.sales = int(input(f'Please enter{emp.name}sales volume:'))
        print(f'{emp.name}What's your salary{emp.get_salary()}')


if __name__ == '__main__':
    main()

Keywords: Python Class OOP

Added by jfeather on Thu, 23 Dec 2021 12:03:36 +0200