Skip to content

Instantly share code, notes, and snippets.

def fibonacci():
x, y = 0, 1
while True:
x, y = y, x + y
yield x
p = fibonacci()
@ZhouYang1993
ZhouYang1993 / InfiniteFibonacciNumber.py
Last active May 29, 2020 02:39
Generators in Python
def fibonacci():
x, y = 0, 1
while True:
x, y = y, x + y
yield x
fib = fibonacci()
@ZhouYang1993
ZhouYang1993 / pipeline.py
Created May 29, 2020 02:48
Generators in Python
def times_two(nums):
for n in nums:
yield n * 2
def natural_number(maximum):
x = 0
while x < maximum:
yield x
x += 1
@ZhouYang1993
ZhouYang1993 / pipeline.py
Created May 29, 2020 02:49
Generators in Python
def times_two(nums):
for n in nums:
yield n * 2
def natural_number(maximum):
x = 0
while x < maximum:
yield x
x += 1
@ZhouYang1993
ZhouYang1993 / example1.py
Last active June 5, 2020 03:49
Understand Constructors in Python Classes
class Student:
def __new__(cls, *args, **kwargs):
print("Running __new__() method.")
instance = object.__new__(cls)
return instance
def __init__(self, first_name, last_name):
print("Running __init__() method.")
self.first_name = first_name
self.last_name = last_name
@ZhouYang1993
ZhouYang1993 / Singleton.py
Created June 5, 2020 04:49
Understand Constructors in Python Classes
class Singleton_Student(object):
_instance = None
def __new__(cls, *args, **kwargs):
print("Running __new__() method.")
if not Singleton_Student._instance:
Singleton_Student._instance = object.__new__(cls)
return Singleton_Student._instance
def __init__(self, first_name, last_name):
@ZhouYang1993
ZhouYang1993 / example3.py
Created June 5, 2020 05:21
Understand Constructors in Python Classes
class Student(object):
def __new__(cls, *args, **kwargs):
print("Running __new__() method.")
return None
def __init__(self, first_name, last_name):
print("Running __init__() method.")
self.first_name = first_name
self.last_name = last_name
@ZhouYang1993
ZhouYang1993 / example1.py
Created June 13, 2020 08:43
Understand the Property Decorator in Python
class Student:
def __init__(self):
self._score = 0
Yang = Student()
print(Yang._score)
# 0
Yang._score = 100
del Yang._score
@ZhouYang1993
ZhouYang1993 / example2.py
Created June 13, 2020 08:53
Understand the Property Decorator in Python
class Student:
def __init__(self):
self._score = 0
def set_score(self, s):
if 0 <= s <= 100:
self._score = s
else:
raise ValueError('The score must be between 0 ~ 100!')
Yang = Student()
@ZhouYang1993
ZhouYang1993 / example3.py
Created June 13, 2020 08:57
Understand the Property Decorator in Python
class Student:
def __init__(self):
self._score = 0
def set_score(self, s):
if 0 <= s <= 100:
self._score = s
else:
raise ValueError('The score must be between 0 ~ 100!')
Yang = Student()