Records学习笔记
1. __getitem__(self, key) 内建方法(Build-in)
例子:
class Test(object): def __getitem__(self, key): print("test") return 1 t = Test() print(t["m"])
运行结果:
>>> hello
>>> 1
2. ___getattr__(self, name) 内建方法(Build-in)
该方法在未找到对象的属性值的时候调用.
例子:
class Test(object):
def __getattr__(self, name):
print("test")
return 1 t = Test()
print(t.m)
运行结果:
>>> hello
>>> 1
去掉__getattr__函数时,会提示没有m这个属性的错误。
3. @property 装饰器
用于将一个函数生产对应的getter函数
实例:
class Test(object):
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name t = Test()
t.name = "hello"
print(t.name)
运行结果:
>>> hello
4. A if 条件 else B(语法)
print("") if __name__=='__main__' else print("")
5. __enter__和__exit__内建方法(Build-in)
用于with语句块,当进入with语句块的时候调用__enter__
当离开with语句块的时候调用__exit__
例子:
class test(object):
def __enter__(self):
print("enter")
return self
def __exit__(self, type, value, traceback):
print("out")
del self
with test() as m:
m.name = 1
print (m.name)
运行结果:
>>> enter
>>> 1
>>> out
6. __iter__(self) 迭代器(Build-in)
通过__iter__函数获得一个迭代器对象, 调用迭代器的next方法不断获得下一个值.
例子:
class test(object):
def __init__(self):
self.a = 1
self.b = 1
def __iter__(self):
return self
def __next__(self):
test = self.a + self.b
self.a, self.b = self.b, test
return self.a
def next(self):
return self.__next__ for i in test():
if i > 1000:
break
print(i)