来自Python的知识

Python知识总结(未完)

前言

安装库速度解决: pip3 install -i https://mirrors.aliyun.com/pypi/simple/ '库名'

需求帮助的基本操作.

>>> a = []
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> help(a.index)
Help on built-in function index:

index(...) method of builtins.list instance
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.

>>> print(dir(__builtins__)) # 查看内置函数.

转码的问题

a = "hello world"
a.encode()  # 转码为二进制类型.
import hashlib
m1 = hashlib.md5(a.encode())    # 创建md5对象, 并给参数值(只接受byte类型)
m1.hexdigest()      # 装换为md5值, 使用md5具有唯一性和值短.

深浅复制

深浅复制问题出现在对数据进行复制后, 对象并未达到真正意义上的复制.

一般在list nest(嵌套) list中讨论该现象.

>>> test0 = [1, 2, 3]
>>> test1 = [test0]
>>> test2 = test1.copy()
>>> import copy
>>> test3 = copy.deepcopy(test1)

当我们改变test0的值.

>>> test0[0] = 0
>>> test1, test2, test3
([[0, 2, 3]], [[0, 2, 3]], [[1, 2, 3]])

可以看出list自带的copy方法并不能满足我们的复制意愿, 即为浅复制, 同为浅复制的操作如list的切片操作.

使用copy模块中的deepcopy方法能到达我们的复制意愿.


set集合

集合: 由无序性, 互异性, 确定性的一个或多个元素构成的整体.

& | - < > ^
交集 并集 差集 包含于 与非集

py解释器的优化机制

我们可能会遇到这样的情况.

>>> a = 1
>>> b = 1
>>> id(a), id(b)
(1570532832, 1570532832)
>>> a is b
True
>>> a = 2222
>>> b = 2222
>>> id(a), id(b)
(1897474540848, 1897474541104)
>>> a is b
False

大概就是这样的情况呢, 这是由于解释器的优化机制, 当变量的value在 -5 到 256 之间时不会被当作两个不同的对象, 我的理解是a, b都指向一个数据空间, 当超出机制范围后就是两个不同的数据空间了.


float类型的非准确计算

float类型的数值被我们称为浮点数, 即小数(日常), 然而实际中的float并不是我们想象中的小数.

float类型的数值计算时有如下问题.

>>> a = 2.2
>>> b = 2
>>> type(a)
<class 'float'>
>>> a - b
0.20000000000000018

可以看出和正常思维来比较, float不精确了.

选择decimal模块可以适当的解决这样的问题, 计算结果是Decimal类型, 可以通过转换得到float值.

>>> import decimal
>>> a = decimal.Decimal('2.2')
>>> b = 2
>>> a - b
Decimal('0.2')

py中的数值和序列类型

python中尽管有各种各样的对象和类型, 但实际上自身的数值类型只有4种, 序列类型有3种.

数值类型:

py中的单例模式

单例模式: 只能创建一个类实例.

在使用类操作时, 实际上__new__会比__init__更先执行.

class Earth:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, 'instance'):
            cls.instance = super().__new__(cls)
        return cls.instance

    def __init__(self):
        self.name = 'earth'

e = Earth()
a = Earth()
print(e, id(e), a, id(a))

输出:

<__main__.Earth object at 0x000001C31F12B748> 1937551570760 <__main__.Earth object at 0x000001C31F12B748> 1937551570760

可以看出e, a实例对象实际为同一个.

hasattr(), getattr()都是去调用__getattribute__(),如果有值那么就出值,没有就查看是否有__getattr__(),有就用,没有就报错.
setattr()调用__setattr__()
hasattr()判读是否有返回值,有就为True,报错就为False.


class多继承mro方法

有那么一种情况, 我们的子类继承了多个父类, 当子类需要使用某个方法而当前类没有, 向父类寻找时, 怎么找,

顺序是怎样的就成了问题. 使用mro()方法可以查看继承顺序.

class A:
    pass


class B:
    pass


class C(A, B):
    pass

print(C.mro())

输出:

[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]

py描述符

描述符: __get__, __set__, __delete__, __del__.

class Myattribute:
    def __get__(self, instance, owner):
        print('get')

    def __set__(self, instance, value):
        print('set')

    def __delete__(self, instance):
        print('del')


class Myclass:
    m = Myattribute()

    def __del__(self):  # 析构函数, 即对象被删除或者程序执行完等条件下执行.
        print('instance delete')


c = Myclass()
c.m     # 调用__get__()
c.m = 1     # 调用__set__()
del c.m     # 调用__delete__() 再调用 __del__()

进制转换函数和内置函数

  • bin(), 转换为二进制.
  • oct(), 转换为八进制.
  • hex(), 转换为十六进制.
  • ord(), 将字符转换成对应的ASCII码值.
  • chr(), 将ASCII码值转换成对应的字符.
  • enumerate(), 返回一个可以枚举的对象.
  • filter(), 过滤器.
  • map(), 加工, 对于参数iterable中的每个元素都应用fuction函数,并返回一个map对象.
  • zip(), 将对象逐一配对.

运算符和魔术方法

# 运算符
__add__(self,other) # x+y
__sub__(self,other) # x-y
__mul__(self,other) # x*y
__mod__(self,other) # x%y
__iadd__(self,other)    # x+=y
__isub__(self,other)    # x-=y
__radd__(self,other)    # y+x
__rsub__(self,other)    # y-x
__imul__(self,other)    # x*=y
__imod__(self,other)    # x%=y

# 魔术方法
__class__   # 查看类名
__base__    # 查看继承的父类
__bases__   # 查看继承的全部父类
__dict__    # 查看全部属性,返回属性和属性值键值对形式
__doc__     # 查看对象文档,即类中的注释(用引号注视的部分)
__dir__     # 查看全部属性和方法

类属性访问

属性访问方法: hasattr(), getattr(), setattr(), delattr()

re = Rectangle() # 矩形类
# 查看属性.
hasattr(re, 'lenght')   # 返回bool值.
getattr(re, 'lenght')   # 返回属性值.
re.__getattribute__('lenght')   # 返回属性值.

# 改.
setattr(re, 'lenght', 6)    # 更改属性值为6.
re.__setattr__('length', 6)     # 如上.

# 增.
re.aaa = 1
setattr(re, 'bbb', 2)   # 设置属性没有该属性就创建.
re.__setattr__('ccc', 3)

# 删除.
delattr(re, 'ccc')
re.__delattr('bbb')
del re

内置装饰器和类装饰器

# 内置的装饰器.
class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        areas = self.length * self.width
        return areas

    @property   # 就像访问属性一样.
    def area(self):
        return self.width *self.length

    @staticmethod   # 静态方法, self在调用时会报错.
    def func():
        print('staticmethod_func')

    @classmethod    # 类方法, cls表示类本身, 如果加上self, 在调用时就要把实例传入.
    def show(cls):
        print(cls)
        print('show func')

# 类装饰器.
class Test_Class:
    def __init__(self, func):
        self.func = func

    def __call__(self):
        print('class')

@Test_Class     # 类也可以做装饰器, 但是需要定义__call__方法.
def func_test():
    print('this is test func.')

猜你喜欢

转载自blog.csdn.net/One_of_them/article/details/81456255