Computer Science/Python
Python Grammar: Things that I forget often
focalpoint
2022. 3. 14. 19:01
1. Use deep copy
list function copy() can be troublesome when the list has mutable objects.
from copy import deepcopy
l1 = [1, 2, [3, 4]]
l2 = l1.copy()
l3 = deepcopy(l1)
l1[1] = 3
l1[2][0] = 4
print(l2)
print(l3)
2. while--else for--else
else part is executed when the loop is stopped by 'break' or when the loop wasn't executed.
i = 0
while i > 10:
print(i)
else:
print('no')
for x in range(10):
if x == 11:
break
else:
print('else part is activated if not broke')
3. Dictionary: get & pop
second parameter can be provided to each function
d = {'a': 'apple', 'b': 'banana', 'c': 'carrot'}
print(d.get('d', False))
print(d.pop('c', 'popped'))
print(d.pop('d', 'popped'))
4. Function parameter passing
def func(param1, param2, *args, **kwargs):
print(f'param1: {param1}')
print(f'param2: {param2}')
print('args: ')
for elem in args:
print(elem)
print('kwargs: ')
for k, v in kwargs.items():
print(k, v)
arr = [2, 3, '4']
dic = {'a': 'app', 'b': 'ban'}
func('p1', 'p2', *arr, **dic)
5. Wrapper
def document(func):
def wrapper(*args, **kwargs):
print(func.__name__)
result = func(*args, **kwargs)
print(result)
return result
return wrapper
@document
def iamfunc(a=1):
return a + 3
x = iamfunc()
print(x)
6. Class properties
class Person:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
p = Person('Bob')
print(p.name)
p.name = 'Morgan'
print(p.name)
7. class method, static method
class A:
count = 0
def __init__(self):
A.count += 1
@classmethod
def HowMany(cls):
return A.count
a1 = A()
a2 = A()
a3 = A()
print(A.HowMany())
class A:
@staticmethod
def swapcase(str, type):
if type == 'lower':
return str.lower()
elif type == 'upper':
return str.upper()
else:
return None
print(A.swapcase('aBC', 'upper'))
8. Magic Method
class Complex:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
def __eq__(self, complex2):
return self.real == complex2.real and self.imag == complex2.imag
def __add__(self, complex2):
return Complex(self.real+complex2.real, self.imag+complex2.imag)
def __str__(self):
return f"{self.real:3.3f}" + ' + ' + f"{self.imag:3.3f}" + "i"
c1 = Complex(3, 4)
c2 = Complex(3, 4)
print(c1 == c2)
print(c1 + c2)
9. Named Tuple
from collections import namedtuple
Point = namedtuple('Point', 'x y z')
p1 = Point(1, 2, 3)
print(p1.x, p1.y, p1.z)
p2 = Point('a', 'b', 'c')
print(p2.x, p2.y, p2.z)
10. Data Class
from dataclasses import dataclass
@dataclass
class Person:
name: str
hobby: str
height: float
age: int = 0
p1 = Person('Morgan', 'Game', 183.3, 28)
print(p1.name, p1.hobby, p1.height, p1.age)