Basic Python and python tutorials
Records Study Notes
Records URL
1. _ getitem _ (self, key) built-in method (Build-in)
Example:
1 class Test(object): 2 3 def __getitem__(self, key): 4 5 print("test") 6 7 return 1 8 9 10 11 t = Test()12 13 print(t["m"])
Running result:
>>> hello>>> 1
2. ___ getattr _ (self, name) built-in method (Build-in)
This method is called when the property value of the object is not found.
Example:
1 class Test(object):2 def __getattr__(self, name):3 print("test")4 return 15 6 t = Test()7 print(t.m)
Running result:
>>> hello>>> 1
When the _ getattr _ function is removed, an error indicating that the attribute m does not exist is displayed.
3. @ property modifier
This function is used to generate a corresponding getter function.
Instance:
class Test(object): @property def name(self): return self._name @name.setter def name(self, name): self._name = namet = Test()t.name = "hello"print(t.name)
Running result:
>>> hello
4. A if condition else B (syntax)
print("1") if __name__=='__main__' else print("2")
5. _ enter _ and _ exit _ built-in methods (Build-in)
Used for with statement blocks. When the with statement block is entered, _ enter _ is called __
When leaving the with statement block, call _ exit __
Example:
1 class test(object): 2 def __enter__(self): 3 print("enter") 4 return self 5 def __exit__(self, type, value, traceback): 6 print("out") 7 del self 8 with test() as m: 9 m.name = 110 print (m.name)
Running result:
>>> enter>>> 1>>> out
6. _ iter _ (self) iterator (Build-in)
Obtain an iterator object through the _ iter _ function, and call the next method of the iterator to continuously obtain the next value.
Example:
1 class test(object): 2 def __init__(self): 3 self.a = 1 4 self.b = 1 5 def __iter__(self): 6 return self 7 def __next__(self): 8 test = self.a + self.b 9 self.a, self.b = self.b, test10 return self.a11 def next(self):12 return self.__next__13 14 for i in test():15 if i > 1000:16 break17 print(i)