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

Python元组与命名元组使用技巧
本文探讨了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
### Python命名元组的使用方法 #### 创建命名元组 为了创建一个命名元组,通常会导入 `collections` 模块并调用其中的 `namedtuple()` 函数。此函数接收两个参数:一个是新型的名称;另一个是要包含在该型内的字段列表或字符串形式的一系列属性名。 ```python import collections # 使用列表定义字段名 Point = collections.namedtuple('Point', ['x', 'y']) # 或者使用空格分隔的字符串定义字段名 Person = collections.namedtuple('Person', 'name age') ``` 一旦定义好之后就可以像常规一样实例化这些对象[^2]。 #### 实例化命名元组 当有了命名元组模板后,便能够轻松地创建具体的实例: ```python p = Point(11, y=22) # 可以混合位置参数和关键字参数 t = Person(name="John", age=30) print(p.x, p.y) # 访问特定成员变量 print(t.name, t.age) ``` 值得注意的是,在初始化过程中既支持按顺序传入值也接受指定键值的方式传递数据[^4]。 #### 修改命名元组的内容 由于命名元组本质上还是不可变序列的一部分,因此无法直接更改其内部元素。不过,如果确实有更新某些部分的需求,则可通过 `_replace()` 方法来构建含有不同数值的新版本的对象而不影响原对象本身[^5]。 ```python new_p = p._replace(x=33) # 返回一个新的 Point 对象,仅改变了 x 的值 print(new_p) updated_t = t._replace(age=31) print(updated_t) ``` 以上就是关于如何利用 Python 构建以及操作命名元组的一些基本知识点[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小基基o_O

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

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

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

打赏作者

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

抵扣说明:

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

余额充值