python module使用之----operator

1.operator
我这里主要可能介绍的是python3.X版本的,会和python2.X版本有点不一致,具体的细节很多,小伙伴们遇到问题还请自行百度吧,LZ也没有足够的能力能够涵盖到所有的问题,只能把我自己遇到的一些问题分享出来,避免小伙伴们再走一遍弯路!

#coding:utf-8

from operator import *

#逻辑操作符(operator的一些操作函数与原本的运算是相同的)
a = [1, 2, 3]
b = a
print ('a =', a)
print ('b =', b)
print
print ('not_(a):', not_(a))
print ('truth(a):', truth(a))
print ('is_(a, b):', is_(a, b))
print ('is_not(a,b):', is_not(a, b))

#比较操作符(这些函数等价于<、<=、==、>=和>的表达式语法)
a = 3
b = 5
print ('a =', a)
print ('b =', b)
print
for func in (lt, le, eq, ne, ge, gt):
    print('{0}(a, b):'.format(func.__name__), func(a, b))

#算术操作符(abs返回值得绝对值,neg返回(-obj), pos返回(+obj))
a, b, c, d = -1, 2, -3, 4
print ('a =', a)
print ('b =', b)
print ('c =', c)
print ('d =', d)
print ('\nPositive/Negative:')
print ('abs(a):', neg(a))
print ('neg(b):', neg(b))
print ('pos(a):', pos(a))
print ('pos(b):', pos(b))


#mod表示取模, mul 表示相乘,pow是次方, sub表示相减
a = -2
b = 5.0
print ('a =', a)
print ('b =', b)
print ('\nArithmetic')
print ('add(a, b):', add(a, b))
print ('div(a, b):', divmod(a, b))
print ('floordiv(a, b):', floordiv(a, b))
print ('mod(a, b):', mod(a, b))
print ('mul(a, b):', mul(a, b))
print ('pow(a, b):', pow(a, b))
print ('sub(a, b):', sub(a, b))
print ('truediv(a, b):', truediv(a, b))


#and 表示按位与, invert 表示取反操作, lshift表示左位移, or表示按位或, rshift表示右位移,xor表示按位异或。
a = 2
b = 6
print ('a =', a)
print ('b =', b)
print ('\nBitwise:')
print ('and_(a, b):', and_(a, b))
print ('invert(a):', invert(a))
print ('lshift(a, b) :', lshift(a, b))
print ('or_(a, b):', or_(a, b))
print ('rshift(a, b):', rshift(a, b))
print ('xor(a, b):', xor(a, b))

#原地操作符
#即in-place操作, x += y 等同于 x = iadd(x, y), 如果复制给其他变量比如z = iadd(x, y)等同与z = x; z += y
a = 3
b = 4
c = [1, 2]
d = ['a', 'b']
print ('a =', a)
print ('b =', b)
print ('c =', c)
print ('d =', d)
print
a = iadd(a, b)
print ('a = iadd(a, b) =>', a)
print
c = iconcat(c, d)
print('c = iconcat(c, d) =>', c)

#属性和元素的获取方法
#operator模块最特别的特性之一就是获取方法的概念,获取方法是运行时构造的一些可回调对象,用来获取对象的属性或序列的内容,获取方法在处理迭代器或生成器序列的时候特别有用,它们引入的开销会大大降低lambda或Python函数的开销
from operator import *
class MyObj(object):
    def __init__(self, arg):
        super(MyObj, self).__init__()
        self.arg = arg
    def __repr__(self):
        return 'MyObj(%s)' % self.arg
objs = [MyObj(i) for i in range(5)]
print ("Object:", objs)
g = attrgetter("arg")
vals = [g(i) for i in objs]
print ("arg values:", vals)
objs.reverse()
print ("reversed:", objs)
print ("sorted:", sorted(objs, key=g))

#属性获取方法类似于:lambda x, n='attrname':getattr(x,nz)

from operator import *
l = [dict(val=-1*i) for i in range(4)]
print ("dictionaries:", l)
g = itemgetter("val")
vals = [g(i) for i in l]
print ("values: ", vals)
print ("sorted:", sorted(l, key=g))
l = [(i,i*-2) for i in range(4)]
print ("tuples: ", l) 
g = itemgetter(1)
vals = [g(i) for i in l]
print ("values:", vals)
print ("sorted:", sorted(l, key=g))

#结合操作符和定制类
#operator模块中的函数通过相应操作的标准Python接口完成工作,所以它们不仅适用于内置类型,还适用于用户自定义类型
from operator import *
class MyObj(object):
    def __init__(self, val):
        super(MyObj, self).__init__()
        self.val = val
        return
    def __str__(self):
        return "MyObj(%s)" % self.val

    def __lt__(self, other):
        return self.val < other.val

    def __add__(self, other):
        return MyObj(self.val + other.val)
a = MyObj(1)
b = MyObj(2)
print (lt(a, b))
print (add(a,b))

#类型检查
#operator 模块还包含一些函数用来测试映射、数字和序列类型的API兼容性
#python2.7支持,python3.5不支持
# from operator import *
# class NoType(object):
#   pass
# class MultiType(object):
#   def __len__(self):
#       return 0

#   def __getitem__(self, name):
#       return "mapping"

#   def __int__(self):
#       return 0

# o = NoType()
# t = MultiType()

# for func in [isMappingType, isNumberType, isSequenceType]:
#   print ("%s(o):" % func.__name__, func(o))
#   print ("%s(t):" % func.__name__, func(t))

#获取对象方法
#使用methodcaller可以获取对象的方法
from operator import methodcaller

class Student(object):
    def __init__(self, name):
        self.name = name

    def getName(self):
        return self.name

stu = Student("Jim")
func = methodcaller('getName')
print (func(stu))   #输出Jim

放出部分运行的截图,因为print函数使用的比较多,所以打印出来的内容比较多,可以注释掉部分或者对着源代码自己看一下。。。

这里写图片这里写图描述

这里举得例子都是比较简单基础的啦O(∩_∩)O

-------------------------------------------- C++ Call Stacks (More useful to developers): -------------------------------------------- Windows not support stack backtrace yet. ------------------------------------------ Python Call Stacks (More useful to users): ------------------------------------------ File "/data/yourenchun/share/projects/renzheng/liuyi/liuyi_env/Python-2.7.14/lib/python2.7/site-packages/paddle/fluid/framework.py", line 1843, in append_op attrs=kwargs.get("attrs", None)) File "/data/yourenchun/share/projects/renzheng/liuyi/liuyi_env/Python-2.7.14/lib/python2.7/site-packages/paddle/fluid/layer_helper.py", line 43, in append_op return self.main_program.current_block().append_op(*args, **kwargs) File "/data/yourenchun/share/projects/renzheng/liuyi/liuyi_env/Python-2.7.14/lib/python2.7/site-packages/paddle/fluid/layers/nn.py", line 9597, in relu6 attrs={'threshold': threshold}) File "/data/yourenchun/share/projects/renzheng/slurm/dist_arcface/models/mnasnet.py", line 171, in conv_bn_layer return fluid.layers.relu6(bn) File "/data/yourenchun/share/projects/renzheng/slurm/dist_arcface/models/mnasnet.py", line 198, in inverted_residual_unit name=name + '_expand') File "/data/yourenchun/share/projects/renzheng/slurm/dist_arcface/models/mnasnet.py", line 252, in invresi_blocks name=name + '_' + str(i + 1)) File "/data/yourenchun/share/projects/renzheng/slurm/dist_arcface/models/mnasnet.py", line 110, in net name='conv' + str(i)) File "test.py", line 107, in run emb = model.net(image) File "test.py", line 318, in main testor.run() File "test.py", line 323, in <module> main() ---------------------- Error Message Summary: ---------------------- Error: Fail to allocate CPU memory: size = 114987136 . [Hint: p should not be null.] at (E:\Paddle\paddle\fluid\memory\detail\system_allocator.cc:61) [operator < relu6 > error]
07-12
根据给出的Python调用栈信息,您遇到了一个内存分配错误。错误消息提示在 E:\Paddle\paddle\fluid\memory\detail\system_allocator.cc 的第 61 行出现了一个空指针错误。同时,调用栈显示了涉及的函数调用序列: 1. 在 "/data/yourenchun/share/projects/renzheng/liuyi/liuyi_env/Python-2.7.14/lib/python2.7/site-packages/paddle/fluid/framework.py" 的第 1843 行,调用了 append_op 函数。 2. 在 "/data/yourenchun/share/projects/renzheng/liuyi/liuyi_env/Python-2.7.14/lib/python2.7/site-packages/paddle/fluid/layer_helper.py" 的第 43 行,调用了 append_op 函数。 3. 在 "/data/yourenchun/share/projects/renzheng/liuyi/liuyi_env/Python-2.7.14/lib/python2.7/site-packages/paddle/fluid/layers/nn.py" 的第 9597 行,调用了 relu6 函数。 4. 在 "/data/yourenchun/share/projects/renzheng/slurm/dist_arcface/models/mnasnet.py" 的第 171 行,调用了 conv_bn_layer 函数。 5. 在 "/data/yourenchun/share/projects/renzheng/slurm/dist_arcface/models/mnasnet.py" 的第 198 行,调用了 inverted_residual_unit 函数。 6. 在 "/data/yourenchun/share/projects/renzheng/slurm/dist_arcface/models/mnasnet.py" 的第 252 行,调用了 invresi_blocks 函数。 7. 在 "/data/yourenchun/share/projects/renzheng/slurm/dist_arcface/models/mnasnet.py" 的第 110 行,调用了 net 函数。 8. 在 "test.py" 的第 107 行,调用了 run 函数。 9. 在 "test.py" 的第 318 行,调用了 model.net(image)。 10. 在 "test.py" 的第 323 行,调用了 testor.run()。 11. 在 "test.py" 的第 323 行,调用了 main 函数。 根据错误消息和调用栈信息,问题可能出现在您的代码中的某个地方导致内存分配失败。您可以检查相关代码,确保内存分配和释放的正确性,并确保所需的内存不超过系统可用内存。此外,还可以考虑减小输入数据的规模或使用更高效的算法来降低内存需求。 如果您需要更详细的帮助,请提供更多关于代码和环境的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值