Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
ZhouYang1993 / example4.py
Created June 13, 2020 09:31
Understand the Property Decorator in Python
class Student:
def __init__(self):
self._score = 0
@property
def score(self):
return self._score
@score.setter
def score(self, s):
@ZhouYang1993
ZhouYang1993 / property_template.py
Created June 13, 2020 09:38
Understand the Property Decorator in Python
class C(object):
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@ZhouYang1993
ZhouYang1993 / another_way.py
Created June 13, 2020 10:01
Understand the Property Decorator in Python
class Student:
def __init__(self):
self._score = 0
def score(self):
return self._score
def set_score(self, s):
if 0 <= s <= 100:
self._score = s
@ZhouYang1993
ZhouYang1993 / read_only_attribute.py
Created June 13, 2020 10:17
Understand the Property Decorator in Python
class Student:
def __init__(self):
self._score = 0
@property
def score(self):
return self._score
@score.deleter
def score(self):
@ZhouYang1993
ZhouYang1993 / example1.py
Created June 22, 2020 21:13
Shallow Copy and Deep Copy in Python
A = [1, 2, 3]
B = A
B.append(4)
print(A)
# [1, 2, 3, 4]
print(B)
# [1, 2, 3, 4]
@ZhouYang1993
ZhouYang1993 / example2.py
Created June 22, 2020 21:32
Shallow Copy and Deep Copy in Python
import copy
A = [1, 2, 3]
# B = A.copy()
B = copy.copy(A) # The same as `B = A.copy()`
B.append(4)
print(A)
# [1, 2, 3]
@ZhouYang1993
ZhouYang1993 / shallowCopy.py
Created June 22, 2020 22:02
Shallow Copy and Deep Copy in Python
import copy
A = [[1, 2], ['a', 'b']]
B = copy.copy(A) # The same as `B = A.copy()`
B.append(4)
print(A)
# [[1, 2], ['a', 'b']]
print(B)
# [[1, 2], ['a', 'b'], 4]
@ZhouYang1993
ZhouYang1993 / deepCopy.py
Created June 22, 2020 22:20
Shallow Copy and Deep Copy in Python
import copy
A = [[1, 2], ['a', 'b']]
B = copy.deepcopy(A)
B.append(4)
print(A)
# [[1, 2], ['a', 'b']]
print(B)
# [[1, 2], ['a', 'b'], 4]
@ZhouYang1993
ZhouYang1993 / example1.py
Created June 23, 2020 20:36
Higher Order Functions in Python
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
@ZhouYang1993
ZhouYang1993 / example3.py
Last active June 23, 2020 21:03
Higher Order Functions in Python
from functools import reduce
city = ['L', 'o', 'n', 'd', 'o', 'n', 2, 0, 2, 0]
city_to_str = reduce(lambda x, y: str(x) + str(y), city)
print(city_to_str)
# London2020