python 小技巧

1、F字符串(F-Strings)

name = "eric"
age = 10
res = f"hi my name is {name} i'm {age} now"
print(res)
"""
hi my name is eric i'm 10 now
res = f"A total number is {2*3}"
print(res)
"""
A total number is 6
"""

2、dir()返回任何对象的属性和方法。

lst = [1,2,3]
print(dir(lst))
"""
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__','__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
"""

3、装饰器。

def logging(func):
    def log_function_called():
        print(f"{func} called")
    return log_function_called

@logging
def my_name():
    print("chris")

my_name()
"""
<function my_name at 0x0000000002BA9AF0> called
"""
def logging(func):
    def log_function_called():
        print(f"{func} called")
        func()
    return log_function_called

@logging
def my_name():
    print("chris")

my_name()
"""
<function my_name at 0x0000000002989AF0> called
chris
"""

 

上一篇:AuthenticateRequest event


下一篇:装饰器_下