The third piece of Python knowledge points for Xiaobai

The python video tutorial column introduces the third Python knowledge point.

This article is the third one, a total of four to lay the foundation of Python

The above two basically get the data structure in Python, and I will spend an article on the most important classes.

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. Classes create a new object, and objects are instances of this class.

Objects can use class variables. Variables belonging to objects or classes are called domains. Objects can also use functions belonging to classes. Such functions are called class methods. Domains and methods can be collectively called class attributes.

There are two types of domains

Those belonging to the instance
belong to the class itself.
They are called instance variables and class variables, respectively.

Classes are created using the keyword 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 called. This special variable refers to the object itself. By convention, its name is self, similar to this in Java.

Pay attention to the following two special methods in the class:

init__ method: call this method when an object of the class is created; equivalent to the constructor in C++, that is, when the 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 called, and __del__ is the last called.

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 writing becomes very simple, everyone can assign access to resources at will. 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

such as:

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 something that many people don't know. Below, I will 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) #Runsenprint (p.__age)

#AttributeError: Person instance has no attribute '__age'#私有变量访问不了,报错复制代码

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

Inheritance is actually 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).

To inherit a class, basically use the following five methods.

8.1 Directly call the parent attribute method;
father has money, but son has no money, so son uses 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 Forced to call the parent private property method;
Dad said, you son, always use my money, I decided to hide private money. Son try super() to get your private money, but here you need to pay attention to super() forcing the parent class private property method to be overridden. Private variables can’t be inherited by the super, and you can’t access the private properties in the parent class. The variable of the attribute method means that the son can't get the private money.

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 Override the parent attribute method;
suddenly the son has money and decides not to use his father's money, but with his own money, he decides to rewrite the parent attribute method.

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 father's money? It is not a private variable, it is not private money, of course you can get it

Let's first see if we can get it without 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 super is like taking money, it's too small for your father and me.

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 Inheriting the parameters in the initialization process of the parent class
Sometimes, dad needs to make money and spend money, which are the parameters in our initialization process. My son is curious and decides to see how much money he needs in his pocket.

Let’s write down earn_money and spend_money 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 over.

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并增加额外参数cclass 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, you can write some cases yourself to deepen your understanding.

9. Input/Output
The interaction between the program and the user requires the use of input/output, which mainly includes the console and files; for the console, input and print can be used. input(xxx) Input xxx, then read the user's input and return.

In [1]: input()1Out[1]: '1'复制代码

10. File input/output
You can use the file class to open a file, and use file read, readline and write to properly read and write the file. 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")
file operation, need to call the close method to close the file. If you use with open, you don't need slave.

And r+, w+, a+

r: only means reading in
r+: both reading and writing to
w: only means writing to
w+: both reading and writing,
but r+ and w+ are different in that it will not empty the original contents in txt , The following is their comparison, anyway, try to use a+, basically there is nothing wrong with it.

Description r + w + a +
current file when the file does not exist to create file creation thrown
open empty Reserved Reserved contents of the original file
00 file initial position of the tail
default jump to the end of file mark writing position of the writing position of mark
supplementary example bar :

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") #默认rwhile 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. Memory
Memory, everyone should not know. Python provides a standard module called pickle. You can use it to store any Python object in a file, and then you can take it out completely. This is called persistent storage of objects; there is another module called cPickle, which has the same functions as Pickle is exactly the same, except that it is written in C, which 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. Abnormality
When some abnormal conditions occur in the program, an abnormality occurs.

Try… except can be used in python.

try:    print (1/0)except ZeropisionError as e:

    print(e)except:

    print( "error or exception occurred.")#integer pision or modulo by zero复制代码

This article comes from the php Chinese website python video tutorial column: https://www.php.cn/course/list/30.html

Guess you like

Origin blog.csdn.net/Anna_xuan/article/details/110085305