内置方法
from collections import namedtuple
free_falling_body = namedtuple('free_falling_body', ['g', 't'])
h = free_falling_body(9.8, 2 ** (1 / 2))
print(h) # 自由落体运动
print(h.g * h.t ** 2 / 2) # 自由落体高度
free_falling_body(g=9.8, t=1.4142135623730951)
9.800000000000002
自写1
class Tuple:
t = ('a', 'b', 'c')
for i in t:
exec("%s='%s'" % (i, i))
print(' '.join(Tuple.t))
print(Tuple.b, Tuple.i)
print(Tuple.__dict__)
打印结果
a b c
b c
{'__module__': '__main__', 't': ('a', 'b', 'c'), 'i': 'c', 'a': 'a', 'b': 'b', 'c': 'c', '__dict__': <attribute '__dict__' of 'Tuple' objects>, '__weakref__': <attribute '__weakref__' of 'Tuple' objects>, '__doc__': None}
自写2
class里面的命名原理展示
class TB:
__prefix = 'HJW_'
_c = 'c'
b = __prefix + 'b'
a = __prefix + 'a'
print(dir(TB))
print([i for i in dir(TB) if not i.startswith('__')])
print([i for i in dir(TB) if not i.startswith('_')])
print()
for i in TB.__dict__.items():
print(*i)
打印结果
['_TB__prefix', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_c', 'a', 'b']
['_TB__prefix', '_c', 'a', 'b']
['a', 'b']
__module__ __main__
_TB__prefix HJW_
_c c
b HJW_b
a HJW_a
__dict__ <attribute '__dict__' of 'TB' objects>
__weakref__ <attribute '__weakref__' of 'TB' objects>
__doc__ None
tuple
class Tuple(tuple):
def __getattr__(self, item):
return self[self.index(item)]
t = Tuple(('aa', 'bb'))
print(t.aa, t.bb) # aa bb
print(t.cc) # ValueError: tuple.index(x): x not in tuple
setattr、getattr、getattribute报错和玩法
报错
d = dict()
d.a = 5 # 报错:`AttributeError: 'dict' object has no attribute 'a'`
d.__setattr__('a', 5) # 报错:`AttributeError: 'dict' object has no attribute 'a'`
报错
class Object:pass
d = Object()
d.__setattr__('a', 5)
print(d.a, d.__getattribute__('a')) # 不报错
print(d['a']) # 报错:`TypeError: 'Object' object is not subscriptable`
报错
class Object:
def __getattr__(self, item):
return item
d = Object()
print(d.aa, d.bb) # aa bb
dict
class Dict(dict):
def __getattr__(self, item):
return self[item]
d = Dict(aa='aa', bb='bb')
print(d.aa, d.bb) # aa bb
print(d.cc) # KeyError: 'cc'
set
class Set(set):
def __getattr__(self, item):
return item if item in self else None
s = Set(('aa', 'bb'))
print(s.aa, s.bb, s.cc) # aa bb None