Created by Junchao
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
Data structure
Control statements
Function
"""Example for defining first class in Python
"""
class FirstClass:
"""Our first class: just a simple demo
A class is a namespace by itself. When seeing the class keyword,
a class definition begins. And when the indentation ends, the class
definition ends and a class object is created.
So a new class is an object--similar to Ruby and you can create a
class from metaclass just like you are about to create an object
from a class. This sounds confusing? Just bear with me for a while.
"""
pass
"""Explaining class-as-a-namespace notion
"""
class ClassAsANamespace:
"""Demo class-as-a-namespace
"""
name1 = 'Hello, World!'
name2 = 1
name3 = [1, 2, 3]
name4 = {
'test': 'Hello, World!'
}
# You cannot use the statement below, as name1 is inside
# ClassAsANamespace's namespace. Uncomment it and see it running
# print(name1)
print(ClassAsANamespace.name1)
print(ClassAsANamespace.name2)
print(ClassAsANamespace.name3)
print(ClassAsANamespace.name4)
"""Creation of objects, name it as create_objects.py
"""
class DemoClass:
"""A demo class for object creation
"""
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def a_method(self):
return self.a
def another_method(self, b):
# notice that here self.b could be different from b. this is because of
# namespace--still remember what is namespace right?--a box full of
# names inside
print('Inside self, the b is ', self.b)
print('The parameter b is ', b)
return self.c + b
a_obj = DemoClass(1, 2, 3)
print('The type of a_obj is ', type(a_obj))
print('The type of a_obj\'s method is ', type(a_obj.a_method))
print('The return value of a_obj.a_method is ', a_obj.a_method())
print('The return value of a_obj.another_method is ', a_obj.another_method(0))
"""More examples on objects creation, same folder as create_objects.py
"""
from create_objects import DemoClass
obj1 = DemoClass(1, 2, 'Hello')
print('obj1\'s b is ', obj1.b)
print(
'Call obj1.another_method for first time: ',
obj1.another_method(' world!')
)
obj1.c = 'I just said "Hello'
print(
'Call obj1.another_method after assignment: ',
obj1.another_method(' world!"')
)
"""Practical examples of classes and objects
Pet is a class: representing the abstraction notion of those lovely animations
that keep us company.
"""
class Pet:
"""A example class to represent pets in real life.
Of course we will not be able to describe every aspect of pets. Just
an example.
"""
healthy_weight_range = (1.5, 4.5)
favorite_foods = ['meat']
def __init__(self, name, age, weight, color):
"""Instantiation method for a pet.
"""
self.name = name
self.age = age
self.weight = weight
self.color = color
def have_birthday(self):
self.age += 1
def eat_stuff(self, food):
if food in self.favorite_foods:
self.weight += 2
else:
self.weight += 0.5
def exercise(self):
self.weight -= 0.5
def check_weight(self):
if self.__is_weight_healthy():
return False
else:
self.send_weight_warning()
return True
def speak(self):
return '{} says love you'.format(self.name)
def send_weight_warning(self):
print('Oh, pleas e take note of my weight')
def __is_weight_healthy(self):
lower, upper = self.healthy_weight_range
if lower <= self.weight and self.weight <= upper:
return True
else:
return False
def __repr__(self):
return self.name
if __name__ == '__main__':
print('Let\'s create some pets')
print('first have a dog')
dog1 = Pet('a little dog', 1, 1.5, 'Black and white')
for _ in range(5):
dog1.eat_stuff('meat')
while not dog1.check_weight():
dog1.exercise()
print(dog1.speak() + '\n')
print('then a cat')
cat1 = Pet('a lovely cat', 2, 1.0, 'Black and white')
cat1.have_birthday()
print('Now {} is turning into {} years old!'.format(repr(cat1), cat1.age))
print(cat1.speak())
"""Demostration of instance methods, class methods and static methods
"""
class MethodsDemoClass:
"""Just to demo use of instance methods, class methods and static methods
"""
var = 'cls'
def __init__(self, var):
self.var = var
def instance_method(self):
return self.var
@classmethod
def class_method(cls):
return cls.var
@staticmethod
def static_method(var):
return var
obj = MethodsDemoClass('object')
print('Calling instance method: ', obj.instance_method())
print('Calling class method: ', MethodsDemoClass.class_method())
print('Calling static method: ', MethodsDemoClass.static_method('static'))
"""Demostration of different notions in advanced object oriented programming
"""
from practical_class_object import Pet
class Dog(Pet):
favorite_foods = ['meat', 'bone']
def speak(self):
return 'woof-woof, {} says love you'.format(self.name)
class Cat(Pet):
favorite_foods = ['meat', 'fish']
def speak(self):
return 'meow-meow, {} says love you'.format(self.name)
class DangerousPet:
def speak(self):
return 'I am just dangerous'
def is_angry(self):
print('Warning!!! Be careful and try not to further piss it off')
class Cheetah(DangerousPet, Pet):
healthy_weight_range = (25, 45)
if __name__ == '__main__':
print('Let\'s create some pets')
print('first have a dog')
dog1 = Dog('a little dog', 1, 1.5, 'Black and white')
for _ in range(5):
dog1.eat_stuff('bone')
while not dog1.check_weight():
dog1.exercise()
print(dog1.speak() + '\n')
print('then a cat')
cat1 = Cat('a lovely cat', 2, 1.0, 'Black and white')
cat1.have_birthday()
for _ in range(5):
cat1.eat_stuff('bone')
print('Now {} is turning into {} years old!'.format(repr(cat1), cat1.age))
print(cat1.speak() + '\n')
print('and a cheetah')
the_cheetah = Cheetah('Handsome and dangerous cheetah', 5, 30, 'yellow and black')
print(the_cheetah.speak())
the_cheetah.is_angry()
A use case diagram at its simplest is a representation of a user's interaction with the system that shows the relationship between the user and the different use cases in which the user is involved.from Wikipedia
from [sourcemaking.com]
In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the relationships among objects.A use case diagram at its simplest is a representation of a user's interaction with the system that shows the relationship between the user and the different use cases in which the user is involved.from Wikipedia
from [tutorialspoint.com]