python learning -- object oriented (elementary)

Posted by Xyphon on Mon, 28 Feb 2022 14:50:43 +0100

class

There are many kinds of life, human, birds, animals and so on. These classes have properties and capabilities that they all share. Then we can use classes to define a human, in which an instantiated variable of human is called an object.

1. Role of class

Similar to a function combining a piece of code, a class can combine variables and functions.

2. Definition of class

Class definition should be capitalized

class Person:  # To define a human, the contents of the class should be indented.
	name = "ice"
	
    def eat(self):
        print("I am eating")

self here will be mentioned later.

3. Class variables

You can use class directly Variable to get the variable of the class, but using the variable directly will report an error. Even in functions in this class, variables cannot be used directly.

print(Person.name)  # ice
print(name)  # report errors

4. Method of class

Same as variable

Person.eat(Person)  # I am eating

5. Class instantiation

Similar to list Sort () is actually a list object, and sort is a method of a list object. An object is actually an instantiated object of a class, which is the same as the variable definition:

ps = Person()  # Instantiate a person

5. Class initialization

This is the common def__ init__ (self): This is the initialization function of the class. It will be called automatically during class instantiation. Similar__ init__ Underlined methods are those already in python, which have special abilities. They are called magic methods, and their names cannot be changed.

class Person:
    name = "ice"

    def eat(self):
        print(f"{self.name} is eating")

    # def __init__(self):
    #     print("I'm instantiating")

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


# ps = Person()  # I'm instantiating
ps1 = Person("ice")  # Instantiate an ice object
ps2 = Person("Ice pigeon")  # Instantiate an ice pigeon object
ps1.eat()  # ice is eating
ps2.eat()  # Ice pigeon is eating

From this we can define two different objects. It is worth noting that when a class does not define def__ init__ (self): when, this class will automatically generate an empty initialization function, but once defined, the empty initialization function will not exist. And a class can only define one initialization function.

6. self in class

When we instantiate an object, this self represents the object. The class function must contain the first parameter, which is generally self. It can be understood that this variable is passed into the function as a parameter. Because it is difficult to use an instantiated object in the function of a class Variable, you can change it to self Variable.

Object oriented and process oriented

For example: eat noodles

  • Facing the process: buy noodles - > wash the pot - > boil water - > cook noodles - > eat noodles
  • Object oriented: entering the canteen - > ordering noodles - > eating noodles

That is, object-oriented encapsulates the operations of buying noodles - > washing pot - > boiling water - > cooking noodles into the canteen - > ordering noodles.

Destructor

The destructor is defined as def__ del__ (self): called automatically when an instantiated object is deleted. We use del to delete objects.

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

    def __del__(self):
        print(f"{self.name} Deleted")


ps1 = Person("ice")
del ps1  # ice has been deleted

Class inheritance and reuse

A class can inherit other classes to gain their capabilities.

1. Succession

For humans, some people mainly eat rice, while others mainly eat noodles, so they can be divided into two classes, but the two classes have too many similarities, which will lead to a lot of code duplication if redefined. So there is inheritance.

class Person:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex

    def eat(self):
        print("Eat white rice")

    def sleep(self):
        print("sleep")


class Sichuan(Person):  # The class inheritance of Sichuan people
    def eat(self):
        print("Sichuan people like to eat hot pot")


ps1 = Person("ice", 19, "man")
# ps2 = Sichuan()  # When a class inherits and has no initialization function, it should also be instantiated like the parent class
ps2 = Sichuan("Ice pigeon", 19, "man")

ps1.sleep()  # sleep
ps1.eat()  # Eat white rice
ps2.sleep()  # sleep

It can be seen from the code that the ps2 object inherits the sleep function of the parent class.
Add that all classes inherit the object class.

2. Reuse

It can be found that the Person class and the Sichuan class share the eat function. When the object ps2 calls the eat function, which one is executed? Obviously, it is the function of the subclass. This is called method reuse.

ps2.eat()  # Sichuan people like to eat hot pot

3. The subclass accesses the parent class

Subclasses can be passed through super() To access the methods or variables of the parent class.

class Sichuan(Person, object):  # The class inheritance of Sichuan people
    def eat(self):
        print("Sichuan people like to eat hot pot")
        super().eat()

In this way, we can eat both hot pot and rice.

Multiple inheritance

Suppose a person from Sichuan and a Cantonese married and gave birth to a mixed race child, then the mixed race child will inherit two classes.

class Sichuan(Person, object):  # The class inheritance of Sichuan people
    def eat(self):
        print("Sichuan people like to eat hot pot")
        super().sleep()


class Guangdong:
    def eat(self):
        print("Cantonese like drinking tea")


class Hunxue(Sichuan, Guangdong):
    def eat(self):
        print("Hybrids like hamburgers")
        super().eat()


hx = Hunxue("Mixed race", 18, "woman")
hx.eat()  # Sichuan people like to eat hot pot

It can be seen that multiple inheritance has priority, and the priority on the left is the highest. Therefore, the output result of the above eat method is that Sichuan people like hot pot.

1. View inheritance order

Use hunxue MRO can get the order of inheritance of mixed blood.

  1. <class '__main__.Hunxue'>
  2. <class '__main__.Sichuan'>
  3. <class '__main__.Guangdong'>
  4. <class '__main__.Person'>
  5. <class 'object'>

It can be seen that Sichuan class has the highest priority. At the same time, it can be found that Sichuan inherits Guangdong, but when we use mro for these two classes alone, there is no direct relationship between them.

Even so, if we add super () to Sichuan's eat on the basis of the above code Eat (), then its output should be executed according to the inheritance order of the starting point (that is, Hunxue). So his output is that Cantonese like drinking tea.

Last practice answer

import datetime


# Use the datetime module to generate txt files of the month and day in batches
import os


def fun1():
    for i in range(1, 31):
        dt = datetime.datetime(2022, 1, i)
        s = dt.strftime("%Y-%m-%d")
        # print(s)
        file = open("../file/" + s + ".txt", "w")


# After generating the above files, write the file name in each file again
def fun2():
    for i in range(1, 31):
        dt = datetime.datetime(2022, 1, i)
        s = dt.strftime("%Y-%m-%d")
        filename = s + ".txt"
        str = "../file/" + filename
        file = open(str, "w")
        file.write(filename)
        file.close()


# Add '' after all file names generated above_ NEW’
def fun3():
    for i in range(1, 31):
        dt = datetime.datetime(2022, 1, i)
        s = dt.strftime("%Y-%m-%d")
        filename = s + ".txt"
        filename_new = "../file/" + filename
        os.rename(filename_new, filename_new + "_NEW")


# Suppose there is an English text file, write a program to read its contents, and change the uppercase letters into lowercase letters, and the lowercase letters into uppercase letters
def fun4():
    file = open("../file/a.txt", "a+")
    file.seek(0)
    str1 = file.readlines()
    file.close()
    file = open("../file/a.txt", "w")
    for i in str1:
        j = i.swapcase()
        file.write(j)
    file.close()


# fun1()
# fun2()
# fun3()
# fun4()

practice

  • Define an account class, which can create accounts, deposits, withdrawals, query balances, and close accounts.
  • Now three people are going to open an account, deposit and close an account respectively. Please use the above class to realize it.

Concluding remarks


ps: now pay attention to me, and you will be an old fan in the future!!!

Next Trailer

Having mastered the definition and basic use of classes before, you can access properties and methods through point operators, but what if the properties do not exist? You don't want to report an error because the attribute doesn't exist. How to avoid this problem?

Topics: Python