python学习日记6-迭代器与单例模式

2024-01-01  本文已影响0人  livein80

迭代器

++++++++++++++++++++++++++++

1.迭代

# 判断对象是否为可迭代
a = [1,2,3,4] #列表
b = (1,2,3,4) #元组
c = {'a':1,'b':2} #字典
s = 'abcd'  # 字符串
n = 123     # 数字

#第一种方法:
from collections.abc import Iterable
print(isinstance(a,Iterable))  #  输出:True
print(isinstance(b,Iterable)) #  输出:True
print(isinstance(c,Iterable)) #  输出:True
print(isinstance(s,Iterable)) #  输出:True
print(isinstance(n,Iterable)) #  输出:False

#第二种方法: 强制转化为迭代器,报错为不可迭代
print(iter(a)) #输出: <list_iterator object at 0x10b163fd0>
print(iter(n)) #输出:TypeError: 'int' object is not iterable

2.单例模式

class Person():
    _instance = None
    def __new__(cls, *args, **kwargs):
        if Person._instance is None:
            print('new')
            Person._instance = super().__new__(cls, *args, **kwargs)
        return Person._instance
    def __init__(self):
        print('init')


p1 = Person()
p2 = Person()
#  new ,init ,init

print(id(p1),id(p2))
# 4442047632 4442047632 4442047632
上一篇下一篇

猜你喜欢

热点阅读