#魔法方法都带__xxxx__双下划线,系统自己调用
#初始化的魔法方法
#__init__(self,...)一定不能有返回值,__new__(cls,...)初始化实例对象第一个调用的
#方法,一定要返回一个实例对象
'''
class CapStr(str):
def __new__(cls,string):
string = string.upper()
return str.__new__(cls,string)
'''
#property的实现原理,描述符相关的魔法方法get(self,instance,owner),set(self,instance,owner),delete(self,instance,owner)
'''
class Celsius:
def __init__(self,value=26.0):
self.value = float(value)
def __get__(self,instance,owner):
return self.value
def __set__(self,instance,value):
self.value=float(value)
class Fahrenheit:
def __get__(self,instance,owner):
print(instance.__dict__)
return instance.cel*1.8 + 32
def __set__(self,instance,owner):
print(instance.__dict__)
instance.cel = (float(value) - 32)/1.8
class temp:
cel = Celsius()
fah = Fahrenheit()
'''
#属性相关的魔法方法,有getattr(访问不存在的属性时候调用),getattributte(self,name),setattr(self,name,value),delattr(self,name)
'''
class Rectangle:
def __init__(self,width=0,height=0):
self.width = width
self.height = height
def __setattr__(self,name,value):
if name == 'square':
self.width = value
self.height = value
else:
super().__setattr__(name,value)#不可以写self.name = value,会造成死循环
def getArea(self):
return self.width * self.height
'''
#‘属性’和’描述符‘魔法方法的关系和区别,1.当这个类中的属性被访问的时候调用属性相关的魔法方法。2.当这个类(A)作为一个实例化对象赋值给另外一个类(B)的属性(X)时,
#实例化B访问属性X就会调用A中的’描述符‘的魔法方法。3.结论是感觉没有什么卵子用啊.
'''
class Pro:
def __getattribute__(self,name):
print('getattribute')
return super().__getattribute__(name)
def __getattr__(self,name):
print('getattr')
#return super().__getattr__(name) AttributeError: 'super' object has no attribute '__getattr__'
def __setattr__(self,name,value):
print('setattr')
super().__setattr__(name,value)
def __set__(self,instance,owner):
print('set')
super().__set__(instance,owner)
def __get__(self,instance,owner):
print('get')
return super().__get__(instance,owner)
'''
#自定义不可变数组,并且记录数组内的访问次数
'''
class CountList:
def __init__(self,*args):
self.value = [x for x in args]
self.count = {}.fromkeys(range(len(self.value)),0)
def __len__(self):
return len(self.value)
def __getitem__(self,key):
self.count[key] += 1
return self.value[key]
'''
#迭代器 iter next 斐波那契数列
'''
class Fibe:
def __init__(self,n=20):
self.a = 0
self.b = 1
self.n = n
def __iter__(self):#返回迭代器本身
return self
def __next__(self):#返回迭代器的规则
self.a,self.b = self.b,self.a+self.b#这个数加上上一个数返回给下一个数
if self.a > self.n:
raise StopIteration
return self.a
'''
#生成器 yield语句 实现斐波那契数列
#for 循环自动调用next和处理StopIteration异常,所以可以对生成器产生作用
'''
def fibe():
a = 0
b = 1
while True:
a,b = b,a+b
yield a
'''
'''
#列表推导
a = [i for i in range(100) if not (i%2) and i%3]#100以内能被2整除不能被3整除
#字典推导
b = {i:i%2 == 0 for i in range(10)}#10以内偶数为True,奇数为False
#集合推导
c = {i * i for i in [1,1,2,3,3,4,5,5,5,6,7,7,8]}#去重 相乘 无序
#生成器推导
d = (i for i in range(10))#用for或者next(d)即可执行生成器
#生成器做函数参数
e = sum(i for i in range(100) if i % 2)
'''