repr()
返回一个对象的 string 格式
class EvalSegErr(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
if 1==1:
raise EvalSegErr({'1':'Smith',2:'William'})
EvalSegErr: {'1': 'Smith', 2: 'William'}
hasattr()
if hasattr(dcm, 'RescaleSlope'):
img = dcm.pixel_array * dcm.RescaleSlope + dcm.RescaleIntercept
itemgetter()
from operator import itemgetter
a={ 'publishing': 64,
'group': 928,
'rudolph': 8,
'and': 17474,
'former': 306,
'consolidated': 37,
'gold': 165}
b=sorted(a, key=itemgetter(1))
rows = [{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}]
rows_by_fname = sorted(rows, key=itemgetter('fname'))
getattr(object, name[, default])
该函数用于返回一个对象属性值,括号里两个值。返回可以是数、string、函数、方法等。
class A(object):
def set(self, a, b):
x = a
a = b
b = x
print (a, b)
a = A()
a1 = getattr(a, 'set')
a1(a='1', b='2')
class B(object):
bar = 1
b = B()
b1=getattr(b, 'bar')
class C(object):
bar = 's'
c = C()
c1=getattr(c, 'bar')
collections.namedtuple
动态的创建一个继承tuple
的子类。跟tuple
相比,返回的子类可以使用名称来访问元素。元素可以是函数。
from collections import namedtuple
Account = namedtuple('a1',["name","pwd",'pn'])
def g1(x):
return x**2+1
obj1 = Account("Jack", "123456",g1)
print(obj1.name)
print(obj1.pwd)
print(obj1.pn)
print(obj1.pn(10))
print(type(obj1))
Jack
123456
<function g1 at 0x7f81b2cb3ae8>
101
<class '__main__.a1'>