Home > Article > Backend Development > The third Python knowledge point compiled for beginners
This article is the third one. There are four articles in total to lay the foundation of Python.
The above two have basically solved the data structure in Python. Let’s talk about it in one article. The most important class.
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 the object is an instance of this class.
Objects can use variables of the class. Variables belonging to the object or class are called domains. Objects can also use functions belonging to the class. Such functions are called class methods. Domains and methods can be collectively called classes. properties.
There are two types of fields
They are called instance variables and classes respectively variable.
A class is created using the keyword class
. 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.
You need to pay attention to the following two special methods in the class:
__init__
method: This method is called when an object of the class is created. ; Equivalent to the constructor in c, that is, when this class is called, the __init__ method will be executed.
__del__
Method: This method is called when the object of the class is destroyed; equivalent to the destructor in c. When using del to delete an object, the __del__ method is also called, and __del__ is the last one called.
All class members (including data members) in Python are public. There are no private classes in Java, that is, everyone has a calling class. Although writing is very simple, However, everyone can allocate and access resources at will, which is indeed a bad thing in the project.
However, Python classes have 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 something that 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 what many people don’t know, the following , 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) #Runsenprint (p.__age) #AttributeError: Person instance has no attribute '__age'#私有变量访问不了,报错复制代码
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 to use all the functionality of an existing class and extend it without having to rewrite the original class.
Inheritance, actually understood this way, is that I wrote a father class and a son class. The father has money, but the son has no money, so the son decided to inherit his father and call his father's money (variables and methods of the father class) .
Inherit a class and basically use the following five methods.
The father has money, but the son has no money, so the son uses his 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复制代码
Dad said, your son always uses my money, so I decided to hide my private money. Son, try super()
to get your private money, but you need to pay attention heresuper()
Forcibly call the parent class's private property method, which is an overriding method. Private variables cannot be supper. If you can't inherit it, you can't access the variables of the private attribute methods in the parent class, that is, the son can't get 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复制代码
Suddenly the son turned out to be rich, and decided not to use his father’s money, but to use his own money, and decided to override the parent class 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复制代码
If the father puts the money in __init__
, whether the son can get the father’s money is not a private variable , it’s not private money, of course you can get it
Let’s see if we can get it without using 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 super is like taking money. You look down on 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复制代码
Sometimes, dad needs to make and spend money, which are the parameters in our initialization process. The son was very curious and decided to take a look at his dad. How much more money do you have in your pocket?
We have written down earn_money and spend_money first here
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并增加额外参数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 and the basic content of calling the attributes and methods of the parent class. You can write some cases yourself to deepen your understanding.
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'复制代码
可以使用file类打开一个文件,使用file的read、readline和write来恰当的读写文件。对文件读写能力取决于打开文件时使用的模式, 常用模式
文件操作之后需要调用close方法来关闭文件。如果用with open就不用slose了。
还有r+,w+,a+
但r+与w+不同的是,不会把原先存在txt中的东西清空,下面是他们的对比,反正尽量用a+,基本没什么错报出来。
描述 | r+ | w+ | a+ |
---|---|---|---|
当前文件不存在时文件 | 抛出异常 | 创建文件 | 创建文件 |
打开后原文件内容 | 保留 | 清空 | 保留 |
初始位置 | 0 | 0 | 文件尾 |
写入位置 | 标记位置 | 标记位置 | 写入时默认跳至文件尾 |
补充个例子吧:
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复制代码
存储器,大家应该不知道。python提供一个标准的模块,成为pickle,使用它可以在一个文件中存储任何python对象,之后可以完整的取出来,这被称为持久地存储对象;还有另外一个模块成为cPickle,它的功能和pickle完全一样,只不过它是用c写的,要比pickle速度快(大约快1000倍)。
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"]复制代码
当程序中出现某些异常的状况时,异常就发生了。
python中可以使用try ... except
处理。
try: print (1/0)except ZeropisionError as e: print(e)except: print( "error or exception occurred.")#integer pision or modulo by zero复制代码
相关免费学习推荐:python视频教程
The above is the detailed content of The third Python knowledge point compiled for beginners. For more information, please follow other related articles on the PHP Chinese website!