python【自写】命名元组【杂耍自用】

内置方法

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小基基o_O

您的鼓励是我创作的巨大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值