python——推导式,可迭代对象,私人变量,自省

推导式的格式:

[处理迭代中的每一个元素 for语句 条件判断]

def test_derivation():
    """
    推导式的格式:
    [处理迭代中的每一个元素  for语句   条件判断]
    """
    # 返回1~100所有的偶数   [2,4,6,8.....100]
    result = []
    for i in range(1, 101):
        if i % 2 == 0:
            result.append(i)
    print(result)

    print([i for i in range(1, 101) if i % 2 == 0])  # 列表推导式   列表解析

    print(["第" + str(i) + "题" for i in range(1, 10)])

    # 还可以应用于字典的解析
    cookie = "_ga=GA1.2.930106050.1598708338; Hm_lvt_39b794a97f47c65b6b2e4e1741dcba38=1601376712,1601378209,1601378225,1601378754; __gads=ID=d51165f71c40f9ea:T=1598708341:R:S=ALNI_MZNqeB0nRFuLFMHnaiqkRUxBzf4FQ; UM_distinctid=176b8fb1876443-00bac4ce20b2-3323767-1fa400-176b8fb18776f; CNZZDATA1278819128=727475643-1609418695-https%253A%252F%252Fwww.baidu.com%252F%7C1609418695; Hm_lvt_e2fcb48ccb07c3714ef5b2d8ebbe5bac=1609421232; .AspNetCore.Antiforgery.b8-pDmTq1XM=CfDJ8EklyHYHyB5Oj4onWtxTnxZK-SyYDsAq4COxRCEyMCXVnz1Dm-qDFJUvwPYvokG_RRwY17vcaB5If8VM7G0ko8cvd0RmS5frC7yOg0-xGo7Xzim9enGJ45ZqPXn24gU1XorwYZg3T2KdYGRMNKBQitw; _gid=GA1.2.1426547664.1614343372"
    # cookie格式:  cookie键1=cookie值1;键2=值2;键3:值3;.....
    # cookie新格式: {键1:值1,键2:值2......}
    new_cookie = {}
    for item in cookie.split(';'):  # 先用;分割cookie
        s = item.split('=')  # 用 = 分割
        new_cookie[s[0]] = s[1]  # =左边作为键,=右边作为值,添加到new_cookie字典中
    print(new_cookie)  # 输出new_cookie
    # 字典推导式  字典解析 格式如下:
    # {键:值  for语句}
    print({item.split('=')[0]: item.split('=')[1] for item in cookie.split(';')})


if __name__ == '__main__':
    test_derivation()

自省

# 自省: 汉语解释为”自我反省“
# Python的自省:Python运行的时候知道对象自身有哪些东西
class Person(object):
    name = "人"


print(dir(Person))  # dir是自省的一种,作用查看自己有哪些属性
print(hasattr(Person, "name"))  # hasattr是自省的一种,作用查看对象有没有某个属性


# 使用场景举例:  “检查函数参数(类型检查isinstance等)”
def f(i):
    if not isinstance(i, int):
        print(f'{i}不是整数')
    else:
        print(f'{i}是整数')


if __name__ == '__main__':
    f(1)
    f(3.1)

"""
dir()  # Python查看对象有哪些属性
hasattr()  # Python查看对象是否有每个属性
type()     # Python查看对象是什么类型
isinstance()  # Python查看对象是不是某个类型
id()  # Python查看对象的id是什么
callable()  # Python判断对象是不是可调用的(即是不是可以加括号调用)
help()  # Python查看某个对象的帮助信息
getattr()  # 获得某个对象的属性
setattr()   # 设置某个对象的属性
"""
print(type(1))

可迭代对象

# 可迭代对象,可以用for操作的对象都是可迭代对象
# list  tuple  str   set  dict
for i in [1, 2, 3]:
    print(i)
print(hasattr(list, "__iter__"))
print(hasattr(tuple, "__iter__"))
print(hasattr(str, "__iter__"))
print(hasattr(set, "__iter__"))
print(hasattr(dict, "__iter__"))
print(hasattr(int, "__iter__"))  # False
for i in 1:  # TypeError: 'int' object is not iterable
    print(i)

私有变量

def test_private_vs_protected_vs_public():
    # public: 共有的
    # protected: 受保护的。  不能被其他文件导入
    # private: “私有的”   你的牙刷
    pass

x = 2
_y = 10  # protected


class A(object):
    def __init__(self):
        self.__z = 2  # 私有属性

    def __some_method(self):  # 私有方法
        print(self)


a = A()

if __name__ == '__main__':
    test_private_vs_protected_vs_public()

posted @ 2022-04-13 16:06  曹_小_伟  阅读(54)  评论(0)    收藏  举报