你没见过的python语法

目录:

1、不一样的列表

2、改变type中的规则,创建类:类属性大写

3、%s字串格式化,不用元组用字典

4、没有参数抛出异常

5、字符串签名加f 格式化字符串

6、attr库

 

 

 


 

1、不一样的列表

list1 = ["a", "b", "c"]
self, *args = list1
print(self)
print(args)

输出:

a
['b', 'c']

  

 

2、改变type中的规则,创建类:类属性大写

class UpperAttrMetaClass(type):
    def __new__(cls, class_name, class_parents, class_attrs):
        # 遍历属性字典,把不是__开头的属性名字变为大写
        newAttr = {}
        for k, v in class_attrs.items():
            if not k.startswith("__"):
                newAttr[k.upper()] = v

        # 方法1:通过‘type’来创建类对象
        # return type(class_name, class_parents, newAttr)


        # 方法2:复用type.__new__方法创建类对象
        # return type.__new__(cls, class_name, class_parents, newAttr)

        # 方法3:使用super方法创建类对象
        return super(UpperAttrMetaClass, cls).__new__(cls, class_name, class_parents, newAttr)


# python3的用法
class Foo(object, metaclass=UpperAttrMetaClass):
    bar = "bip"


# 判断Foo类中是否有某个属性
print(hasattr(Foo, 'bar'))
print(hasattr(Foo, "BAR"))

f = Foo()
print(f.BAR)

输出:

False
True
bip

  

3、%s字串格式化,不用元组用字典

str= """
第一个:%(delim)s
第二个:%(id)s
"""
str_new = str % {'delim': "$", 'id': 9}
print(str_new)

输出:

第一个:$
第二个:9

  

4、没有参数抛出异常

def func1(*args, **kwargs):
    if not args:  # 无参数报错
        raise TypeError("descriptor 'format' of 'Formatter' object needs an argument")
    else:
        n_args = len(args)
        pattern = " ".join("%s," for x in range(n_args))
        # print(pattern)
    return "I am func1, my args is: " + pattern % args


if __name__ == '__main__':
    # 有参数正常
    res1 = func1("a1", "a2", "a3")
    print(res1)

    # 无参数报错
    res2 = func1()
    print(res2)

  

输出:

I am func1, my args is: a1, a2, a3,

Traceback (most recent call last):
  File "D:/aaa-py/tmp/my00-tool.py", line 17, in <module>
    res2 = func1()
  File "D:/aaa-py/tmp/my00-tool.py", line 3, in func1
    raise TypeError("descriptor 'format' of 'Formatter' object needs an argument")
TypeError: descriptor 'format' of 'Formatter' object needs an argument

  

5、字符串签名加f 格式化字符串

例子:

https://blog.youkuaiyun.com/sunxb10/article/details/81036693

 

6、attr库

https://www.attrs.org/en/latest/glossary.html 

  

转载于:https://www.cnblogs.com/andy9468/p/9716231.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值