[Python Basics 3] Super detailed tutorial for entry-level friends

foreword

Previous articles:

[Python Basics 1] Super detailed tutorial for entry-level friends

[Python Basics 2] Super detailed tutorial for entry-level friends

7. Object-oriented programming

Everything is an object, and Python certainly supports object-oriented programming. Classes and objects are the two main aspects of object-oriented programming, a class creates a new object, and an object is an instance of this class.

Objects can use class variables, and variables belonging to objects or classes are called fields; objects can also use functions belonging to classes, and such functions are called class methods; fields and methods can be collectively called class attributes.

Domains are of two types

  • Belonging to the instance
  • belongs to the class itself

They are called instance variables and class variables respectively.

Classes are created using keywords class, and the fields and methods of the class are listed in an indented block.

The method of the class must have an additional first parameter, but this parameter is not assigned a value when it is called. This special variable refers to the object itself. By convention, its name is self, similar to this in Java.

The following two special methods in the class need attention:

  • __init__Method: Call this method when an object of the class is created; it is equivalent to the constructor in C++, that is, when this class is called, then the __init__ method will be executed.

  • __del__Method: This method is called when the object of the class is destroyed; it is equivalent to the destructor in C++. When using del to delete an object, the __del__ method is also called, and __del__ is called last.

All class members (including data members) in Python are public. There is no private class in Java, that is, everyone has a calling class. Although the writing becomes very simple,
everyone can allocate access to resources at will. In the project is indeed a bad thing.

But the Python class has private variables and private methods. This is an exception. If the data member used is prefixed with a double underscore, it is a private variable.

You instantiate this class and cannot access it. This is what many people ignore

for example:

class public():
    _name = 'protected类型的变量'
    __info = '私有类型的变量'
    def _f(self):
        print("这是一个protected类型的方法")
    def __f2(self):
        print('这是一个私有类型的方法')
    def get(self):
        return(self.__info)
pub = public()
# 先打印可以访问的
print(pub._name)
pub._f()
####结果如下####
protected类型的变量
这是一个protected类型的方法


# 打印下类 私有变量和私有方法
print(pub.__info)
报错:'public' object has no attribute '__info'
pub._f2()
报错:pub._f2()

But private properties and methods can be called in the same class

pub.get()
#######
'私有类型的变量'

The above is unknown to many people. Next, let me declare a Person class

   
class Person():
    Count = 0
    def __init__(self, name, age):
        Person.Count += 1
        self.name = name
        self.__age = age
    
p = Person("Runsen", 20)

print(p.Count)

# 1 说明我实例化,这个__init__方法就要执行


print(p.name) #Runsen
print (p.__age) 
#AttributeError: Person instance has no attribute '__age'
#私有变量访问不了,报错

8. Inheritance

Object-oriented programming (OOP), English full name: Object Oriented Programming, one of the main functions of object-oriented programming is "inheritance". Inheritance refers to the ability to use all the functionality of an existing class and extend those functionality without rewriting the original class.

Inheritance, in fact, is understood in this way, that is, I wrote a father class and a son class. The father has money, but the son has no money, so the son decides to inherit the father and call the father's money (variables and methods of the father class).

Inherit a class and basically use the following five methods.

8.1 Directly call the parent class attribute method;

The father has money, but the son has no money, so the son uses the father's money

class Father():
    def __init__(self):
        self.money= 1000 
    def action(self):
        print('调用父类的方法')
 
class Son(Father):
    pass
 
son=Son()     # 子类Son 继承父类Father的所有属性和方法
son.action()  # 调用父类属性
输出:调用父类的方法
son.money     # 调用父类属性
输出:1000

8.2 Forcibly call the parent class private property method;

Dad said, your son always uses my money, so I decided to hide my money. Son, try super()to take your private money, but here you need to pay attention super()to forcing the parent class private attribute method to be called, which is to override the method. Private variables cannot be inherited by supper, and you cannot access the variables of the private attribute method in the parent class, that is The son can't get the money from his private house.

class Father():
    __money  = 1000 #私有变量是继承不了
    
    def __action(self):  # 父类的私有方法
        money = 1000
        print('调用父类的方法')
 
class Son(Father):
        
    def action(self):
        super()._Father__action()
        print(money) 
        
son=Son()
son.action() 

调用父类的方法
name 'money' is not defined

8.3 Rewrite parent class attribute method;

All of a sudden, the son was rich, so he decided not to use his father's money, but to use his own money, and decided to rewrite the property method of the parent class.

class Father():
    def __init__(self):
        self.money = 0
    
    def action(self):
        print('调用父类的方法')
 
class Son(Father):
    def __init__(self):
        self.money = 1000
      
    def action(self):
        print('子类重写父类的方法')
 
son=Son()     # 子类Son继承父类Father的所有属性和方法
son.action()  # 子类Son调用自身的action方法而不是父类的action方法
son.money     # 自己的1000

8.4 Calling the __init__ method of the parent class

If the father puts the money in __init__, is it possible for the son to get the money from the father, it is not a private variable, it is not private money, of course he can get it

Let's see if we can get it if we don't use super.

class Father():
    def __init__(self):
        self.money = 1000
 
class Son(Father):
    def __init__(self):
        pass
    
son=Son()
print(son.money)

# 报错:'Son' object has no attribute 'money'

Not even using the super is like taking money. You underestimate your father and me too much.

class Father():
    def __init__(self):
        self.money = 1000
 
class Son(Father):
    def __init__(self):
        super().__init__()
        #也可以用 Father.__init__(self)  这里面的self一定要加上(上面两个相同)
        
        
son=Son()
print(son.money) 

1000

8.5 Inherit the parameters in the initialization process of the parent class

Sometimes, Dad needs to earn and spend money, which are the parameters in our initialization process. The son is very curious and decides to see how much money Dad needs in his pocket.

We have written earn_money and spend_money here first

class Father():
    def __init__(self):
        self.earn_money=1000
        self.spend_money= -500
 
class Son(Father):
    def __init__(self):
        super().__init__()
        #也可以用 Father.__init__(self)  这里面的self一定要加上
        
    def add(self):
        return self.earn_money+self.spend_money
        
        
son=Son()
print(son.add())

500

The son found that his father did not have enough money, so he secretly took some money.

class Father():
    def __init__(self,a,b):
        self.earn_money = a
        self.spend_money= b
    def add(self):
        return self.a + self.b
 
#调用父类初始化参数a,b并增加额外参数c
class Son(Father):
    def __init__(self,a,b,c=1000):  # c固定值
        Father.__init__(self,a,b)  
        self.son_money = c
        
    def add(self):
        return self.earn_money+self.spend_money + self.son_money
        
   
        
son=Son(1000,-500)   # 所以c可以不用显示表达出来
print(son.add())     # 调用子类add函数

1500

The above basically covers the inheritance of Python classes, the basic content of calling the attributes and methods of the parent class, and you can write some cases by yourself to deepen your understanding.

9. Input/output

The interaction between the program and the user needs to use input/output, mainly including the console and files; for the console, input and print can be used. input(xxx) enters xxx,
then reads the user's input and returns.

In [1]: input()
1
Out[1]: '1'

10. File input/output

You can use the file class to open a file, and use file's read, readline, and write to read and write the file appropriately. The ability to read and write files depends on the mode used when opening the file,
common mode

  • read mode ("r")
  • write mode ("w")
  • append mode("a")

After the file operation, you need to call the close method to close the file. If you use with open, you don't need slose.

And r+, w+, a+

  • r: just means read
  • r+: can both read and write
  • w: just means write
  • w+: both read and write

However, the difference between r+ and w+ is that it will not clear the original contents in txt. The following is their comparison. Anyway, try to use a+ as much as possible, and there is basically no misreporting.

describe r+ in+ a+
file when the current file does not exist Throw an exception Create a file Create a file
Original file content after opening reserve empty reserve
initial position 0 0 end of file
write location mark location mark location Skip to the end of the file by default when writing

Add an example:

test = '''\
This is a program about file I/O.
Author: Runsen
Date: 2020/3/31
'''
f = open("test.txt", "w") 
f.write(test) 
f.close() 

f = open("test.txt") #默认r
while True:
    line = f.readline()
    if len(line) == 0:  
        break
    print(line)
f.close()

######
This is a program about file I/O.

Author: Runsen

Date: 2020/3/31

11. Storage

Memory, you should not know. Python provides a standard module called pickle, which can store any python object in a file and then take it out completely. This is called persistent storage object; there is another module called cPickle, its function and Pickle is exactly the same, except that it is written in C and is faster than pickle (about 1000 times faster).

import pickle

datafile = "data.data"

mylist = ["Runsen", "is", "20"]

f = open("test.txt", "wb+")
pickle.dump(mylist, f)
f.close()

del mylist

f = open(datafile,'rb+')
mylist = pickle.load(f)

print(mylist)
#["Runsen", "is", "20"]

12. Abnormal

Exceptions occur when certain unusual conditions occur in a program.

Processing is available in python try ... except .

try:
    print (1/0)
except ZeroDivisionError as e:
    print(e)
except:
    print( "error or exception occurred.")

#integer division or modulo by zero

At last

Baozi, who just started to get in touch with Python, you can private message me if you don’t understand anything

I've also prepared tons of free video tutorials, PDF e-books, and source code! Just pick up the business card at the end of the article!

Guess you like

Origin blog.csdn.net/yxczsz/article/details/128644612