Python之面向对象slots与迭代器协议

  slots:

 # class People:
# x=1
# def __init__(self,name):
# self.name=name
# def run(self):
# pass # print(People.__dict__)
#
# p=People('alex')
# print(p.__dict__) class People:
__slots__=['x','y','z'] p=People()
print(People.__dict__) p.x=1
p.y=2
p.z=3
print(p.x,p.y,p.z)
# print(p.__dict__) p1=People()
p1.x=10
p1.y=20
p1.z=30
print(p1.x,p1.y,p1.z)
print(p1.__dict__)

  item系列:

 #把对象操作属性模拟成字典的格式
class Foo:
def __init__(self,name):
self.name=name
def __setattr__(self, key, value):
print('setattr===>')
def __getitem__(self, item):
# print('getitem',item)
return self.__dict__[item]
def __setitem__(self, key, value):
print('setitem-----<')
self.__dict__[key]=value
def __delitem__(self, key):
self.__dict__.pop(key)
# self.__dict__.pop(key)
# def __delattr__(self, item):
# print('del obj.key时,我执行')
# self.__dict__.pop(item) f=Foo('George')
f.name='Wang'
f['name']='George'
# print(f.name)
# f.name='George'
# f['age']=18
# print(f.__dict__)
#
# del f['age'] #del f.age
# print(f.__dict__) # print(f['name'])

  __next__、__iter__ 实现迭代器协议:

 # from collections import Iterable,Iterator
# class Foo:
# def __init__(self,start):
# self.start=start # def __iter__(self):
# return self # def __next__(self):
# return 'aSB' # f=Foo(0)
# f.__iter__()
# f.__next__() # print(isinstance(f,Iterable))
# print(isinstance(f,Iterator)) # print(next(f)) #f.__next__()
# print(next(f)) #f.__next__()
# print(next(f)) #f.__next__() # for i in f: # res=f.__iter__() #next(res)
# print(i) # from collections import Iterable,Iterator
# class Foo:
# def __init__(self,start):
# self.start=start # def __iter__(self):
# return self # def __next__(self):
# if self.start > 10:
# raise StopIteration
# n=self.start
# self.start+=1
# return n # f=Foo(0) # print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f)) # for i in f:
# print('====>',i) # class Range:
# '123'
# def __init__(self,start,end):
# self.start=start
# self.end=end # def __iter__(self):
# return self # def __next__(self):
# if self.start == self.end:
# raise StopIteration
# n=self.start
# self.start+=1
# return n # for i in Range(0,3):
# print(i) # print(Range.__doc__) class Foo:
'我是描述信息'
pass class Bar(Foo):
pass
print(Bar.__doc__) #该属性无法继承给子类 b=Bar()
print(b.__class__)
print(b.__module__)
print(Foo.__module__)
print(Foo.__class__) #?
05-07 10:15