python
_ & *_ placeholders
if we define these functions:
1 | def f(): |
and we only want some of the outputs:
1 | x,y,_=f() |
the second and third error can be avoided with:
1 | x,y,*_=g() |
generator
the element in generator can be calculate according to some algorithm while all of the list element exist since the list are created.
1 | L =[x*x for x in range(10)] #list |
use next or loop to call generator
1 | next(g) |
super()
- if we want to call the function in the parent class, we can use
super(), for instance:1
2
3
4
5
6
7
8class A:
def spam(self):
print('A.spam')
class B(A):
def spam(self):
print('B.spam')
super().spam # call parent spam() - another common usage is to ensure that the father class is initialized correctly:notes: python 3 can replace
1
2
3
4
5
6
7
8class Base:
def __init__(self):
print('Base.init')
class A(Base):
def __init__(self):
super().__init__()
print('A.init')super(class,self).xxxin python 2 withsuper().xxx
setattr & getattr & delattr
these three are default functions that are responsible for setting/getting/deleting attribute
https://zhuanlan.zhihu.com/p/62569340
enumerate
enumerate(sequence,[start=0]) returns a tuple containing a count(from start which defaults to 0) and the values obtained from iterating over iterable.
it allows us to loop over something and have an automatic counter.
normal loop
1 | i=0 |
using enumerate
1 | seq=['a','b','c'] |
@property & @xxx.setter
@property can transform a method of the class to attribute of the class(which is read only). And the @xxx.setter is responsible for transforming the method to the setter.
1 | class A: |
notes: _x in code above can not be x, otherwise it will report error.read more
*args & **kwargs (positional argument and keyword argument)
you can pass argument of unknown numbers to the function. ‘unknown’ means that it doesn’t know how many arguments the users will pass.
the * is necessary, you can also write *a, **k
the differences between *args and **kwargs:
- *args is non keyword arguments, actually a tuple or list?
- **kwargs is keyword arguments, actually a dict
- *args must be in the front of **kwargs