python 备忘(内置函数)


  • 5个带key内置函数 1.filter/map(function, iterable)-->迭代器 2.sorted(iterable[, cmp[, key[, reverse]]]) -->list 3.min/max(iterable, *[, default=obj, key=func]) -> value
CLICK ME
  1. max

#count函数先理解
a = [1,2,3,3,2,2,2,2]
print(a.count(2)) # 5
print(max(set(a),key=a.count)) #2


# max() 方法返回给定参数的最大值,参数可以为序列。
lis = [1,2,3,-4]
print(max(lis)) #返回lis列表中的最大值
'''结果:
3
'''

print(max(lis,key=abs)) #key参数指向绝对值函数,返回的结果是-4
  1. min
#(2)min
# min() 方法返回给定参数的最小值,参数可以为序列。
lis = [-1,0,1,2]
print(min(lis)) #返回lis列表中的最小值
'''结果:
-1
'''
  1. fileter
'''
unittest源码中
'''
    def getTestCaseNames(self, testCaseClass):
        """Return a sorted sequence of method names found within testCaseClass
        """
        #这里定义filter函数
        def shouldIncludeMethod(attrname):
            if not attrname.startswith(self.testMethodPrefix):
                return False
            testFunc = getattr(testCaseClass, attrname)
            if not callable(testFunc):
                return False
            fullName = f'%s.%s.%s' % (
                testCaseClass.__module__, testCaseClass.__qualname__, attrname
            )
            return self.testNamePatterns is None or 
                any(fnmatchcase(fullName, pattern) for pattern in self.testNamePatterns)

        #filter 使用方法
        testFnNames = list(filter(shouldIncludeMethod, dir(testCaseClass)))

        #是否排序
        if self.sortTestMethodsUsing:

            #testFnNames是列表,sort是python3里面的列表方法
            #case的排序
            testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
        return testFnNames


# filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象。
# 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回
# True 的元素放到新列表中。

# 语法格式:filter(function, iterable)

#实例1
def is_odd(x):
    return x % 2 == 1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9]))) #python3中不使用list强转数据类型的话,filter返回的是迭代器
'''结果:
[1, 3, 5, 7, 9]
'''

#实例2
s = 'jason lv'
iterator = filter(lambda x : x !='a',s)
s1 = ''
for i in iterator:
    s1 += str(i)
print(s1)
'''结果:
json lv
'''

  1. map
# map() 会根据提供的函数对指定序列做映射。
# 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回一个迭代器对象。

# 语法格式:map(function, iterable, ...)

#实例1
def pow2(x):
    return x * x

lis = [1,2,3,4,5,6]
print(list(map(pow2,lis)))
'''结果:
[1, 4, 9, 16, 25, 36]
'''

#实例2
lis = [1,2,3,4,5,6]
print(list(map(lambda x : x *10 if x >3 else x / 2,lis)))
'''结果:
[0.5, 1.0, 1.5, 40, 50, 60]
'''
  1. sorted 注意不是Sort函数是list列表中的函数
#(5)sorted
# Sort函数是list列表中的函数,而sorted可以对list或者iterator进行排序。

# 语法格式:sorted(iterable[, cmp[, key[, reverse]]])
# 参数说明:
# (1) cmp参数
# cmp接受一个函数,拿整形举例,形式为:
# def f(a, b):
#     return a - b
#
# 如果排序的元素是其他类型的,如果a逻辑小于b,函数返回负数;a逻辑等于b,函数返回0;a逻辑大于b,函数返回正数就行了
# (2)key参数
# key也是接受一个函数,不同的是,这个函数只接受一个元素, 形式如下
# def f(a):
#     return len(a)
#
# key接受的函数返回值,表示此元素的权值,sort将按照权值大小进行排序
#
# (3)reverse参数
# 接受False
# 或者True
# 表示是否逆序

# 语法格式:sorted(iterable[, cmp[, key[, reverse]]])
#实例1
lis = [3,2,1,4,5,6]
print(list(sorted(lis,reverse=True)))
'''结果
[6, 5, 4, 3, 2, 1]
'''

print(list(sorted(lis)))    #默认不指定reverse参数时,顺序是正序
'''结果
[1, 2, 3, 4, 5, 6]
'''

#实例2
lis = ['adf ee','zcv','qwer','a s s w']
print(list(sorted(lis,key=len)))
'''结果:
['zcv', 'qwer', 'adf ee', 'a s s w']
'''
  1. fileter


  • map
CLICK ME
'''
unittest源码中
'''
    def loadTestsFromTestCase(self, testCaseClass):
        """Return a suite of all test cases contained in testCaseClass"""        
        if issubclass(testCaseClass, suite.TestSuite):
            raise TypeError("Test cases should not be derived from "
                            "TestSuite. Maybe you meant to derive from "
                            "TestCase?")
        testCaseNames = self.getTestCaseNames(testCaseClass)
        if not testCaseNames and hasattr(testCaseClass, 'runTest'):
            testCaseNames = ['runTest']

        #map(function, iterable) 返回迭代器
        loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
        return loaded_suite

'''
其他示例
'''
# 使用 lambda 匿名函数
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

  • 字符串切片汇总
CLICK ME
  1. [:-1]和[::-1]
a='python'
b=a[::-1] #nohtyp  #从后往前数的话,最后一个位置为-1
c=a[::-2] #nhy
d=a[:-1]  #从位置0到位置-1之前的数  #pytho
e=a[:-2]  #从位置0到位置-2之前的数   #pyth

'''
b = a[i:j]   表示复制a[i]到a[j-1],以生成新的list对象
当i缺省时,默认为0,即 a[:3]相当于 a[0:3]
当j缺省时,默认为len(alist), 即a[1:]相当于a[1:10]
当i,j都缺省时,a[:]就相当于完整复制一份a
'''
'''
b = a[i:j:s]表示:i,j与上面的一样,但s表示步进,缺省为1.
所以a[i:j:1]相当于a[i:j]
当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1
所以a[::-1]相当于 a[-1:-len(a)-1:-1],也就是从最后一个元素到第一个元素复制一遍,即倒序。

'''


  • str/print 的一些方法
CLICK ME
print("I'm %s. I'm %d year old" % ('Vamei', 99))

name = 'Eric'
print(f'Hello, my name is {name}')

print("{1} {0} {1}".format("hello", "world") )

print("网站名:{name}, 地址 {url}".format(name="test", url="www.test.com"))
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C    '))
print("I'm %(name)s. I'm %(age)d year old" % {'name':'Vamei', 'age':99})

'''
HTMLTestRunner.py
'''
line = self.HEADING_ATTRIBUTE_TMPL % dict(
    name = saxutils.escape(name),
    value = saxutils.escape(value),
  )

  • python的一些std,错误Exception处理
CLICK ME
import traceback
import sys

try:
     raise ValueError('this is a exp')

except Exception as ex:
    ex_type, ex_val, ex_stack = sys.exc_info()
    print(ex_type)
    print(ex_val)
    print(ex_stack)
    for stack in traceback.extract_tb(ex_stack):
        print(stack)

  • and or 赋值相关操作
CLICK ME

优先级or要低,n > 1 and 'errorClass'中 n >1 为true 就看and 后面的 errorClass也为true 整个就是true不用看or后面的,就返回了errorClass


'''
看到HTMLTestRunner有个表达式
'''
n =2
style = n > 1 and 'errorClass' or n > 0 and 'failClass' or 'passClass'
print(style)  # passClass

'''
简化版
'''
test = '' or [] or {}
print(test)  # {}



  • callable函数
CLICK ME

对于函数、方法、lambda 函式、 类以及实现了 _call_ 方法的类实例, 它都返回 True。

>>>callable(0)
False
>>> callable("runoob")
False
 
>>> def add(a, b):
...     return a + b
... 
>>> callable(add)             # 函数返回 True
True
>>> class A:                  # 类
...     def method(self):
...             return 0
... 
>>> callable(A)               # 类返回 True
True
>>> a = A()
>>> callable(a)               # 没有实现 __call__, 返回 False
False
>>> class B:
...     def __call__(self):
...             return 0
... 
>>> callable(B)
True
>>> b = B()
>>> callable(b)               # 实现 __call__, 返回 True
True

  • 双下"_ _"方法汇总一下
CLICK ME
  1. 基础
  • getattr/setattr/delattrgetattribute

定义了__getattr__(),当访问object不存在的属性时会调用该方法
不定义访问不存在的属性时会报 AttributeError

进阶:

'''
runner.py
'''
#这样定义过后原来的属性调用和返回值的调用方式一致,增加了换行功能
self.stream = _WritelnDecorator(stream)


class _WritelnDecorator(object):
    """Used to decorate file-like objects with a handy 'writeln' method"""
    def __init__(self,stream):
        self.stream = stream

    def __getattr__(self, attr):
        if attr in ('stream', '__getstate__'):
            raise AttributeError(attr)
        return getattr(self.stream,attr)

    def writeln(self, arg=None):
        if arg:
            self.write(arg)
        self.write('
') # text-mode streams translate to 
 if needed

  • getiterm/setiterm/deliterm/

  • new/init

  • dict/str/repr
class Animal(object):
    run = True
class Dog(Animal):
    fly = False
    def __init__(self, age):
        self.age = age
    def sound(self):
        return "wang wang~"

# 实例化一个对象dog
dog = Dog(1)
# 查看dog对象的属性
print ('dog.__dict__:',dog.__dict__)
# 查看类Dog的属性
print ('Dog.__dict__:',Dog.__dict__)
# 查看类Animal的属性
print ('Animal.__dict__:',Animal.__dict__)

#结果 (和dir区别)
#属性在哪个对象上定义,便会出现在哪个对象的__dict__中
dog.__dict__: {'age': 1}
Dog.__dict__: {'__doc__': None, 'fly': False, '__module__': '__main__', '__init__': <function Dog.__init__ at 0x00000220DB9CB400>, 'sound': <function Dog.sound at 0x00000220DDE4FC80>}
Animal.__dict__: {'run': True, '__dict__': <attribute '__dict__' of 'Animal' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Animal' objects>, '__doc__': None}
  • name/qualname

  • class
class Person(object):
   pass
p= Person()

print(p.__class__)
print(Person.__class__)
  1. 进阶
  • add/sub

  • _import_

  • _mro_/slot/

get(),set(),delete()

https://www.cnblogs.com/andy1031/p/10923834.html

拥有这个方法的类,应该(也可以说是必须)产生一个实例,并且这个实例是另外一个类的类属性(注意一定是类属性,通过self的方式产生就不属于__get__范畴了)。
也就是说拥有这个方法的类,那么它的实例应该属于另外一个类/对象的一个属性。

非资料描述器,也就是只有__get__,不管是类还是实例去访问,默认都获得的是__get__的返回值,但是,如果中间有任何一次重新赋值,那么,这个实例获得的是新的值(对象),已经和原来的描述器完全脱离了关系
资料描述器,比如有__set__方法,后期通过实例对描述器进行赋值,那么访问的是__set__,并且永远关联起来。但是如果通过修改类属性的方式复制,那么也会被重新获取新的值(对象)。

# __get__ 的使用
class TestDes:
    def __get__(self, instance, owner):
        print(instance, owner)
        return 'TestDes:__get__'


class TestMain:
    des = TestDes()


if __name__ == '__main__':
    t = TestMain()
    print(t.des)
    print(TestMain.des)


# __get__ __set__ 的使用
class TestDes:
    def __get__(self, instance, owner):
        print('TestDes:__get__:', instance, owner)
        return 'TestDes:__get__return'

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


class TestMain:
    des = TestDes()


if __name__ == '__main__':
    t = TestMain()
    print(t.des)
    print(TestMain.des)

    print('*************************')

    t.des = 1
    print(t.des)
    print(TestMain.des)

    print('*************************')

    TestMain.des = 1
    print(t.des)
    print(TestMain.des)

'''
TestDes:__get__: <__main__.TestMain object at 0x06C04C70> <class '__main__.TestMain'>
TestDes:__get__return
TestDes:__get__: None <class '__main__.TestMain'>
TestDes:__get__return
*************************
TestDes:__set__: <__main__.TestMain object at 0x06C04C70> 1
TestDes:__get__: <__main__.TestMain object at 0x06C04C70> <class '__main__.TestMain'>
TestDes:__get__return
TestDes:__get__: None <class '__main__.TestMain'>
TestDes:__get__return
*************************
1
1
'''


#描述符Str
class Str:
    def __get__(self, instance, owner):
        print('Str调用')
    def __set__(self, instance, value):
        print('Str设置...')
    def __delete__(self, instance):
        print('Str删除...')

#描述符Int
class Int:
    def __get__(self, instance, owner):
        print('Int调用')
    def __set__(self, instance, value):
        print('Int设置...')
    def __delete__(self, instance):
        print('Int删除...')

class People:
    name=Str()
    age=Int()
    def __init__(self,name,age): #name被Str类代理,age被Int类代理,
        self.name=name
        self.age=age

#何地?:定义成另外一个类的类属性

#何时?:且看下列演示

p1=People('alex',18)

#描述符Str的使用
p1.name
p1.name='egon'
del p1.name

#描述符Int的使用
p1.age
p1.age=18
del p1.age

#我们来瞅瞅到底发生了什么
print(p1.__dict__)
print(People.__dict__)

#补充
print(type(p1) == People) #type(obj)其实是查看obj是由哪个类实例化来的
print(type(p1).__dict__ == People.__dict__)
  1. 高级
  • call

  • iter

  • enter/exit

  • metaclass



  • next、iter的应用
CLICK ME

next、iter组合起来的用发
1.

def test(context=False, **kwargs):
    k, v = next(iter(kwargs.items()))
    print(k,v)               # 可以获取到第一参数的kv值
    k,v ,g= kwargs.items()   # kwargs 传入3个这里就要写3个了。。。
    print(k[0],k[1])

  • property
CLICK ME

title

 1 class Foo:
 2     def get_AAA(self):
 3         print('get的时候运行我啊')
 4 
 5     def set_AAA(self,value):
 6         print('set的时候运行我啊')
 7 
 8     def delete_AAA(self):
 9         print('delete的时候运行我啊')
10     AAA=property(get_AAA,set_AAA,delete_AAA) #内置property三个参数与get,set,delete一一对应
11 
12 f1=Foo()
13 f1.AAA
14 f1.AAA='aaa'
15 del f1.AAA

  • dir
CLICK ME

不太理解为啥叫dir



  • python的os操作
CLICK ME

title



  • things
CLICK ME

title



  • things
CLICK ME

title



原文地址:https://www.cnblogs.com/amize/p/13260945.html