小言_互联网的博客

Python——关于参数&&函数工具&&正则表达式

477人阅读  评论(0)

关于参数

Arbitrary Positional Arguments

  • 任意位置参数,在一个位置参数前面添加星号
def say_hi(*names):
    for name in names:
        print(f'Hi, {name}!')
say_hi()
say_hi('ann')
say_hi('mike', 'john', 'zeo')

函数内部把names当作一个容器进行处理,所以可以传入任意容器:
list tuple dict set iterator generator
注:调用时容器前需要添加*

Arbitrary Keyword Argument

  • 任意关键字参数
def say_hi(**names_greetings):
    for name, greeting in names_greetings.items():
        print(f'{greeting}, {name}!')
        
a_dictionary = {'mike':'Hello', 'ann':'Oh, my darling', 'john':'Hi'}
say_hi(**a_dictionary)

say_hi(**{'mike':'Hello', 'ann':'Oh, my darling', 'john':'Hi'})

注:调用时字典前添加**

参数列表中参数类型顺序

Order of Arguments

1.Positional
2.Arbitrary Positional
3.Keyword
4.Arbitrary Keyword

检测的时候从函数的参数列表开始检测,如果第一个参数是位置参数,则无论如何会将传递进来的第一个形参赋值给位置参数

def say_hi(*names, greeting='Hello', capitalized=False):
    for name in names:
        if capitalized:
            name = name.capitalize()
        print(f'{greeting}, {name}!')

# say_hi('mike', 'john', 'zeo')
say_hi('mike', 'yiya','Hi','asd',greeting='hi')

注:上例中greeting是可选参数

函数工具

  • DIG

Iterator

  • pyhon中所有的容器,都是用for…in…进行循环遍历
  • 内建函数iter()可以把对象转换为可迭代对象,即支持for…in…和next()语句
a = {'1':'a','2':'b'}
h = iter(a)
a[next(h)]
a[next(h)]

创建迭代器

class Counter(object):
    def __init__(self, start, stop):
        self.current = start
        self.stop = stop
    # 约定俗成的写法
        def __iter__(self):
        return self
    def __next__(self):
        if self.current > self.stop:
            raise StopIteration
        else:
            c = self.current
            self.current += 1
        return c

c = Counter(201, 203)

注:迭代器是一个类,它的每一个对象都是一个可迭代的对象

Generator

  • 支持for…in…和next()语句

生成器函数

def counter(start, stop):
    while start <= stop:
        yield start
        start += 1
for i in counter(101, 105):
    print(i)

类实现__iter___方法

class Itercounter():
    def __init__(self, start, stop):
        self.start = start
        self.stop = stop

    def __iter__(self):
        while self.start <= self.stop:
            yield self.start
            self.start += 1

print(sum(Itercounter(101, 105)))

生成器表达式

even = (e for e in range(10) if not e % 2)

生成器表达式代替列表推导式

  • 当输入数据较大的时候,列表推导式可能会占用较大内存
  • 通过next(g)方法可以依次产生输出值,避免内存用量问题

Decorator

  • 装饰器是一个函数,对某个函数进行包装,返回包装后的函数
  • 用来改变函数的行为
def a_decorator(func):
    def wrapper():
        print('We can do sth. before calling a_func...')
        func()
        print('... and we can do sth. after it was called...')
    return wrapper

@a_decorator
def a_func():
    print("Hi, I'm a_func!")
    
a_func()

Decorator Wiki

https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize

正则表达式

  1. matching username
    /^[a-z0-9_-]{3,16}$/
  2. matching password
    /^[a-z0-9_-]{6,18}$/
  3. matching a HEX value
    [/^#?([a-f0-9]{6}|[a-f0-9]{3})$/]
  4. matching a slug
    /^[a-z0-9-]+$/
  5. matching email address
    [/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/]
  6. matching a URL
    [/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/]
  7. matching an IP address
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
  8. matching a HTML tag
    /^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/

转载:https://blog.csdn.net/qq_41809896/article/details/101474245
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场