python from beginner to proficient 2

1.Python object-oriented

Example:

class MyClass:
    """一个简单的类实例"""
    i = 12345
    def f(self):
        return 'hello world'
 
# 实例化类
x = MyClass()
 
# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x.i)
print("MyClass 类的方法 f 输出为:", x.f())

Class methods:

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
# 实例化类
p = people('runoob',10,30)
p.speak()

The attribute i of the MyClass class is: 12345
The output of method f of MyClass class is: hello world

1.Inheritance

The subclass (DerivedClassName) will inherit the properties and methods of the parent class (BaseClassName)

Single inheritance

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
 
 
 
s = student('ken',10,60,3)
s.speak()
ken said: I am 10 years old and I am in grade 3

The print statement above can be rewritten as:

print(f'{self.name}说: 我{self.age}岁,读{self.grade}年级')

multiple inheritance

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
 
#另一个类,多继承之前的准备
class speaker():
    topic = ''
    name = ''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
 
#多继承
class sample(speaker,student):
    a =''
    def __init__(self,n,a,w,g,t):
        student.__init__(self,n,a,w,g)
        speaker.__init__(self,n,t)
 
test = sample("Tim",25,80,4,"Python")
test.speak()   #方法名同,默认调用的是在括号中参数位置排前父类的方法

2. Method rewriting

If the function of your parent class method cannot meet your needs, you can override the method of your parent class in the subclass

# 定义父类
class parent:
    def mymethod(self):
        print('调用父类方法')

# 定义子类
class child(parent):
    def mymethod(self):
        print('调用子类方法')

# 子类实例
c = child()
 # 子类调用重写方法
c.mymethod()
#用子类对象调用父类已被覆盖的方法
super(Child,c).myMethod()
Call subclass method
Call parent class method

3. Class attributes and methods

Class private properties

__private_attrs : Beginning with two underscores , declares that the attribute is private and cannot be used or directly accessed outside the class. When using self.__private_attrs in a method inside a class  .

class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量
 
    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print (self.__secretCount)
 
counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount)  # 报错,实例不能访问私有变量

class methods

Inside a class, use the def keyword to define a method. Unlike general function definitions, class methods must contain the parameter self, which is the first parameter. self represents an instance of the class.

The name of self is not rigid, you can also use this, but it is best to use self according to the convention.

private method of class

__private_method : Starting with two underscores , the method is declared as a private method, which can only be called inside the class and cannot be called outside the class. self.__private_methods .

class Site:
    def __init__(self, name, url):
        self.name = name       # public
        self.__url = url   # private
 
    def who(self):
        print('name  : ', self.name)
        print('url : ', self.__url)
 
    def __foo(self):          # 私有方法
        print('这是私有方法')
 
    def foo(self):            # 公共方法
        print('这是公共方法')
        self.__foo()
 
x = Site('菜鸟教程', 'www.runoob.com')
x.who()        # 正常输出
x.foo()        # 正常输出
x.__foo()      # 报错

2. Python errors and exceptions

1.Exception handling

Exception catching can use try/except statement.

while True:
    try:
        x = int(input('请输入一个数字:'))
        break
    except ValueError:
        print('您输入的不是数字,请尝试重新输入')

        

 An except clause can handle multiple exceptions at the same time. These exceptions will be placed in parentheses to form a tuple, for example:

except (RuntimeError, TypeError, NameError):
    pass

2. Throw an exception

Python uses the raise statement to throw a specified exception.

grammar:

raise [Exception [, args [, traceback]]]


x = 10
if x > 5:
    raise Exception('x不能大于5,x的值为:{}'.format(x))

class MyError(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
try:
        raise MyError(2*2)
    except MyError as e:
        print('My exception occurred, value:', e.value)

Python Basics (9): Errors and Exceptions_Python Exceptions and Errors-CSDN Blog

 3.python os module

1.Common operations of os module

import os
# os.getcwd() 获取当前工作路径
p = os.getcwd()
# D:\python基础学习\初级基础
print(p)

# os.chdir() 切换工作路径
m = os.chdir('D:/python基础学习')
print(m)  #None

# os.environ 获取所有的环境变量
n = os.environ
# print(n)

# os.getlogin()返回通过控制终端进程进行登录的用户名
a = os.getlogin()
print(a)

# os.name 返回python运行的环境系统
b = os.name
print(b)

# os.mkdir 创建一个新的文件价夹,不能创建多级的文件夹
# 当文件夹已经存在时会报错FileExistsError
# 创建多级的文件夹会报错FileNotFoundError

c = os.mkdir('test')
print(c)

# os.makedirs() 创建多级目录
# 创建a文件夹,并且在a文件夹下创建b文件夹
d = os.makedirs('a/b')
print(d)

  • os.rmdir() deletes empty folders
    if the deleted folder is not emptyOSError: [WinError 145] 目录不是空的。'filename'
  • os.removedirs() removes directories recursively.
    Works like rmdir(), except that if the last level directory is successfully removed, removedirs() will try to remove each parent directory mentioned in path in turn until an error is thrown (but the error will be Ignored as this usually means the parent directory is not empty)
  • os.remove() deletes files
  • os.rename(src, dst) renames the file or path (folder), and moves the folder
    src. The original path and the modified name of dst
    can only rename  src the last path or file name of the original path, and all intermediate paths must be must exist, otherwise it will throwFileNotFoundError
  • os.renames(old, new) recursively renames directories or files.
  • Works like rename(), except that the intermediate directories required for the new path are first created. After renaming, removedirs() will be called to remove unnecessary directories in the old path.

 2.os.path module

  • os.path gets the path of the current environment
  • os.path.abspath(path) returns the absolute path of path path
  • os.path.exists(path) determines whether the path or file exists
    path: path
    returns a Boolean value, True, False
  • os.path.getatime(path) returns the last access time of path. The returned time is seconds (timestamp). You can use tiem to convert it into a commonly used time format.
  • os.path.getctime(path) gets the creation time of the file under Windows, and returns the last modification time under Unix.
  • os.path.getsize(path) gets the size of the file
  • os.path.split() splits the path path into a pair, namely (head, tail), where tail is the last part of the path, and head contains everything except the last part. The tail part will not contain a slash, and if path ends with a slash, tail will be empty. If there are no slashes in path, head will be empty. If path is empty, both head and tail are empty.
    The returned part is a tuple consisting of two elements
  • os.path.isfile() determines whether the incoming file exists and returns a Boolean value
  • os.path.isdir() # Determine whether the file path exists and return a Boolean value
# 根据相对路径返回绝对路径
print(os.path.abspath('a/c/aaa.txt'))

# 检查文件是否存在
print(os.path.exists('a/c'))
# 检查aaa.txt文件是否存在
print(os.path.exists('a/c/aaa.txt'))

# 返回文件a最后的访问时间
print(os.path.getatime('a'))

t = os.path.getatime('a')  # 获取时间戳
tupTime = time.localtime(t)  # 将时间戳转换成本地时间
stadardTime = time.strftime("%Y-%m-%d %H:%M:%S", tupTime)  # 转换成对应的时间格式
print(stadardTime) # 2022-09-18 11:44:28

# 获取aaa.txt文件的创建时间(windows)
t = os.path.getctime('a/c/aaa.txt')

# 获取文件aaa.txt的大小
os.path.getsize('a/c/aaa.txt')

a = os.path.split('D:/aa/bb')
print(type(a))  # <class 'tuple'>
print(a)       #  ('D:/aa', 'bb')  头部和尾部

# 当最后为’/‘时
a = os.path.split('D:/aa/bb/')
print(a)     # ('D:/aa/bb', '')  尾部为空
# 当路径path中没有路径的时候 
a = os.path.split('aa')
print(a)  # ('', 'aa')  # 头部为空
 
# 当传入的路径为空时
a = os.path.split( '')
print(a)  # ('', '')  # 头部和尾部均为空

# 判断文件是否存在
os.path.isfile('a/c/aaa.txt')

# 判断路径a/c是否存在
os.path.isdir('a/c')


 3.os.open() module

  • os.open() is a series of operations to open a file. The
    usage is very similar to the basic open function.
os.open(file, flags[, mode])
'''
file 文件名
flags  模式
mode 可选参数, mode 设置其权限状态
'''

mode parameter:

字符       意义
'r'       文本读取(默认)
'w'       文本写入,并先清空文件(慎用),文件不存在则创建
'x'       文本写,排它性创建,如果文件已存在则失败
'a'	      文本写,如果文件存在则在末尾追加,不存在则创建

 4. Python file operations

open(file, mode='r', encoding=None)
 
#file 包含文件名的字符串,可以是绝对路径,可以是相对路径。
#mode 一个可选字符串,用于指定打开文件的模式。默认值 r 表示文本读。
#encoding 文本模式下指定文件的字符编码
# open打开文件
fb = open(file=r'D:\python基础学习\初级基础\分支语句\a.txt',mode='r',encoding='utf-8')
# 读取文件
ct = fb.read()
# 打印文件内容
print(ct)
# 手动关闭文件
fb.close()

with + open(文件地址)as 函数名:
不需要你手动调用fs.close()
自动帮你关闭文件
 
with open(file=r"a.txt",mode="r",encoding="utf-8") as fb:
    ct = fb.read()
    print(ct)

 Binary reading: # mode=rb, no encoding parameter is required

# mode=rb,不需要encoding参数
with open(file=r"a.txt",mode="rb") as fb:
    content  =fb.read()
    print(content)
 
 
#响应:
b'\xe8\xbf\x99\xe9\x87\x8c\xe6\x98\xaf\xe7\xac\xac\xe4\xb8\x80\xe8\xa1\x8c\xe5\x8f\xa5\xe5\xad\x90\r\n\xe8\xbf\x99\xe6\x98\xaf\xe6\x98\xaf\xe7\xac\xac\xe4\xba\x8c\xe8\xa1\x8c\xe5\x8f\xa5\xe5\xad\x90\r\n\xe8\xbf\x99\xe9\x87\x8c\xe6\x98\xaf\xe7\xac\xac\xe4\xb8\x89\xe8\xa1\x8c\xe5\x8f\xa5\xe5\xad\x90\r\n'

 write file

mode="w":

with open(file=r'a.txt',mode='w',encoding='utf-8') as fb:
    fb.write('我就是写入的内容')

 Write binary file: Write the binary information of the image into the file and save it locally

import requests
url = 'https://pics4.baidu.com/feed/6c224f4a20a4462378cd6e8eaf21e7060df3d7e7.png@f_auto?token=233072b88414d0254ef5f233d9271209'

response = requests.get(url)

with open('疯批少女','wb') as f:
    f.write(response.content)
    

Guess you like

Origin blog.csdn.net/m0_74421072/article/details/135313687