1. 程式人生 > >你沒見過的python語法

你沒見過的python語法

line self 方法 formatter def 正常 用法 tool mos

你沒見過的python語法


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

  

  

  

你沒見過的python語法