# 紀錄單一科目的成績 & 算出平均
class SimpleGradebook(object):
def __init__(self):
self._grades = {}
def add_student(self, name):
self._grades[name] = []
def report_grade(self, name, score):
self._grades[name].append(score)
def average_grade(self, name):
grades = self._grades[name]
return sum(grades)/len(grades)
book = SimpleGradebook()
book.add_student("Maomao")
book.report_grade("Maomao", 100)
book.report_grade("Maomao",90)
print(book.average_grade("Maomao"))
95.0
# 記錄多個科目的成績 & 算出平均
class BySubjectGradebook(object):
def __init__(self):
self._grades = {}
def add_student(self, name):
self._grades[name] = {}
def report_grade(self, name, subject, score):
by_subject = self._grades[name]
grade_list = by_subject.setdefault(subject, [])
grade_list.append(score)
def average_grade(self, name):
graby_subject = self._grades[name]
total, count = 0, 0
for grades in graby_subject.values():
total += sum(grades)
count += len(grades)
return total/count
book = BySubjectGradebook()
book.add_student("Maomao")
book.report_grade("Maomao", "Math", 100)
book.report_grade("Maomao", "Math", 90)
book.report_grade("Maomao", "Cooking", 96)
book.report_grade("Maomao", "Cooking", 97)
print(book.average_grade("Maomao"))
95.75
# 記錄多個科目的不同權重的成績 & 算出平均
class WeightedGradebook(object):
def __init__(self):
self._grades = {}
def add_student(self, name):
self._grades[name] = {}
def report_grade(self, name, subject, score, weight):
by_subject = self._grades[name]
grade_list = by_subject.setdefault(subject, [])
grade_list.append((score, weight))
def average_grade(self, name):
graby_subject = self._grades[name]
total, count = 0, 0
for grades in graby_subject.values():
for score, weight in grades:
total += score*weight
count += weight
return total/count
book = WeightedGradebook()
book.add_student("Maomao")
book.report_grade("Maomao", "Math", 100, 1)
book.report_grade("Maomao", "Math", 90, 2)
book.report_grade("Maomao", "Cooking", 96, 3)
book.report_grade("Maomao", "Cooking", 97, 1)
print(book.average_grade("Maomao"))
95.0
import collections
Human = collections.namedtuple("Human", ("name", "gender", "age"))
maomao = Human(name="Maomao", gender="girl", age="18")
Ivan = Human("Ivan", "boy", "25")
print(maomao.name,"is a", maomao.age, "years-old", maomao[1])
print(Ivan[0],"is a", Ivan[2], "years-old", Ivan.gender)
maomao.age = "20"
Maomao is a 18 years-old girl Ivan is a 25 years-old boy
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-79-0f38e149ab14> in <module>() 7 print(Ivan[0],"is a", Ivan[2], "years-old", Ivan.gender) 8 ----> 9 maomao.age = "20" AttributeError: can't set attribute
import collections
Grade = collections.namedtuple("Grade", ("score", "weight"))
class Subject(object):
def __init__(self):
self._grades = []
def report_grade(self, score, weight):
self._grades.append(Grade(score, weight))
def average_grade(self):
total, count = 0, 0
for grade in self._grades:
total += grade.score*grade.weight
count += grade.weight
return total/count
class Student(object):
def __init__(self):
self._subjects = {}
def subject(self, name):
if name not in self._subjects:
self._subjects[name] = Subject()
return self._subjects[name]
def average_grade(self):
total, count = 0, 0
for subject in self._subjects.values():
total += subject.average_grade()
count += 1
return total/count
class Gradebook(object):
def __init__(self):
self._students = {}
def student(self, name):
if name not in self._students:
self._students[name] = Student()
return self._students[name]
book = Gradebook()
maomao = book.student("Maomao")
math = maomao.subject("Math")
math.report_grade(100, 2)
math.report_grade(90, 1)
print(math.average_grade())
cook = maomao.subject("Cooking")
cook.report_grade(85, 1)
cook.report_grade(95, 3)
print(cook.average_grade())
print(maomao.average_grade())
96.66666666666667 92.5 94.58333333333334
# 指定給變數
def hello(name):
print("Hello", name, "!")
a = hello
a("maomao")
Hello maomao !
# 傳入函式當作參數
def compute(func, number1, number2):
return func(number1, number2)
def add(number1, number2):
return number1+number2
def sub(number1, number2):
return number1-number2
n1 = 10
n2 = 5
print(n1, "+", n2, "=", compute(add, n1, n2))
print(n1, "-", n2, "=", compute(sub, n1, n2))
10 + 5 = 15 10 - 5 = 5
# 從函式中傳回當作回傳值
def pow_func(base_num):
def inner_func(num):
return num**base_num
return inner_func
pow_2 = pow_func(2)
print(pow_2(2))
print(pow_2(3))
4 9
# 根據字串長度來排序
def sort_func(x):
return len(x)
names = ["Socrates", "Archimedes", "Plato", "Aristotle"]
names.sort(key=sort_func)
print(names)
names2 = ["Socrates", "Archimedes", "Plato", "Aristotle"]
names2.sort(key=lambda x: len(x), reverse=True)
print(names2)
['Plato', 'Socrates', 'Aristotle', 'Archimedes'] ['Archimedes', 'Aristotle', 'Socrates', 'Plato']
from collections import defaultdict
def key_missing():
print("Assign default value")
return 1
scores = {"Maomao": 100, "Abby": 90}
scores2 = defaultdict(key_missing, scores)
print(scores2["Tom"])
print(scores) # 注意: "Tom" 沒有真的被放進 scores,它是存在在 scores2 裡
print(scores2)
Assign default value 1 {'Maomao': 100, 'Abby': 90} defaultdict(<function key_missing at 0x7f6bb95d68c8>, {'Tom': 1, 'Maomao': 100, 'Abby': 90})
scores2["Hopper"] += 5
for key, value in scores2.items():
print (key, value)
Assign default value Tom 1 Maomao 100 Hopper 6 Abby 90
current = {"green": 12, "blue": 3}
increments = [("red", 5), ("blue", 17), ("orange", 9)]
# Case 1
def increment_with_report(current, increments):
added_count = 0
def missing():
nonlocal added_count
added_count += 1
return 0
result = defaultdict(missing, current)
for key, amount in increments:
result[key] += amount
return result, added_count
result, added_count = increment_with_report(current, increments)
print(result)
print(added_count)
defaultdict(<function increment_with_report.<locals>.missing at 0x7f6bb9ef4b70>, {'red': 5, 'orange': 9, 'blue': 20, 'green': 12}) 2
# Case 2
class CountMissing(object):
def __init__(self):
self.added = 0
def missing(self):
self.added += 1
return 0
counter = CountMissing()
result = defaultdict(counter.missing, current)
for key, amount in increments:
result[key] += amount
print(result)
print(counter.added)
defaultdict(<bound method CountMissing.missing of <__main__.CountMissing object at 0x7f6bb960b8d0>>, {'red': 5, 'orange': 9, 'blue': 20, 'green': 12}) 2
# Case 3
class BetterCountMissing(object):
def __init__(self):
self.added = 0
def __call__(self):
self.added += 1
return 0
counter = BetterCountMissing()
result = defaultdict(counter, current)
for key, amount in increments:
result[key] += amount
print(result)
print(counter.added)
defaultdict(<__main__.BetterCountMissing object at 0x7f6bb95c5588>, {'red': 5, 'orange': 9, 'blue': 20, 'green': 12}) 2
__call__
特殊方法能讓一個類別的實體被當作函式呼叫__call__
方法的類別,而非使用有狀態的 closureclass Animal(object):
def __init__(self, name):
self.name = name
def say_hello(self):
raise NotImplementedError
class Human(Animal):
def say_hello(self):
print("Hi~ I'm human {}".format(self.name))
class Cat(Animal):
def say_hello(self):
print("Meow~ I'm cat {}".format(self.name))
maomao = Human("maomao")
maomao.say_hello()
kitty = Cat("kitty")
kitty.say_hello()
Hi~ I'm human maomao Meow~ I'm cat kitty
class Test(object):
def say_hello(self):
print("Hi~")
object1 = Test()
object1.say_hello() # work
Test.say_hello() # not work
Hi~
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-0d9f59356d68> in <module>() 6 object1.say_hello() 7 ----> 8 Test.say_hello() TypeError: say_hello() missing 1 required positional argument: 'self'
# 紀錄該類別總共有幾個實例物件
class Test(object):
# 類別屬性
instance_number = 0
def __init__(self, name):
# 類別屬性
Test.instance_number += 1
# 實例屬性
self.name = name
def say_hello(self):
print("Hi {}".format(self.name))
@classmethod
def count(cls):
print(cls.instance_number)
Test.count() # work
object1 = Test("object1")
Test.count()
object1.count() # also work
object2 = Test("object2")
Test.count()
object1.count()
object2.count()
0 1 1 2 2 2
class Test(object):
hello_msg = "Hi"
def __init__(self, name):
self.name = name
def say_hello(self):
print(Test.hello_msg, self.name)
@classmethod
def modify_hello_msg(cls, new_msg):
cls.hello_msg = new_msg
object1 = Test("object1")
object1.say_hello()
object2 = Test("object2")
object2.say_hello()
Hi object1 Hi object2
Test.modify_hello_msg("Hey")
object1.say_hello()
object2.say_hello()
object3 = Test("object3")
object3.say_hello()
Test.modify_hello_msg("Welcome")
object1.say_hello()
object2.say_hello()
object3.say_hello()
Hey object1 Hey object2 Hey object3 Welcome object1 Welcome object2 Welcome object3
class Test(object):
def instance_method(self):
print(self)
@classmethod
def class_method(cls):
print(cls)
object1 = Test()
Test.class_method()
object1.class_method()
object1.instance_method()
<class '__main__.Test'> <class '__main__.Test'> <__main__.Test object at 0x7f6bbaffd160>
import platform
class Test(object):
@staticmethod
def preparation():
sysstr = platform.system()
if(sysstr =="Windows"):
print("preparation for Windows platform")
elif(sysstr == "Linux"):
print("preparation for Linux platform")
elif(sysstr == "Darwin"):
print("preparation for Mac OS platform")
else:
print("preparation for Other OS platform")
def do_something(self):
self.preparation()
print("do something ......")
Test.preparation() # work
object1 = Test()
object1.preparation() # also work
print()
object1.do_something() # also work
preparation for Linux platform preparation for Linux platform preparation for Linux platform do something ......
import os
class InputData(object):
def read(self):
raise NotImplementedError
class PathInputData(InputData):
def __init__(self, path):
super().__init__()
self.path = path
def read(self):
return open(self.path).read()
def generate_inputs(data_dir):
for name in os.listdir(data_dir):
yield PathInputData(os.path.join(data_dir, name))
class Worker(object):
def __init__(self, input_data):
self.input_data = input_data
self.result = None
def map(self):
raise NotImplementedError
def reduce(self, other):
raise NotImplementedError
# newline 計數器
class LineCountWorker(Worker):
def map(self):
data = self.input_data.read()
self.result = data.count("\n")
def reduce(self, other):
self.result += other.result
def create_workers(input_list):
workers = []
for input_data in input_list:
workers.append(LineCountWorker(input_data))
return workers
from threading import Thread
def execute(workers):
threads = [Thread(target=w.map) for w in workers]
for thread in threads: # 線程啟動
thread.start()
for thread in threads: # 等待所有線程結束
thread.join()
first, rest = workers[0], workers[1:]
for worker in rest: # 回收處理結果
first.reduce(worker)
return first.result
def mapreduce(data_dir):
inputs = generate_inputs(data_dir)
workers = create_workers(inputs)
return execute(workers)
print("There are {} lines".format(mapreduce("/home/maomao/tmp")))
There are 77 lines
import os
class GenericInputData(object):
def read(self):
raise NotImplementedError
@classmethod
def generate_inputs(cls, config):
raise NotImplementedError
class PathInputData(GenericInputData):
def __init__(self, path):
super().__init__()
self.path = path
def read(self):
return open(self.path).read()
@classmethod
def generate_inputs(cls, config):
data_dir = config["data_dir"]
for name in os.listdir(data_dir):
yield cls(os.path.join(data_dir, name))
class GenericWorker(object):
def __init__(self, input_data):
self.input_data = input_data
self.result = None
def map(self):
raise NotImplementedError
def reduce(self, other):
raise NotImplementedError
@classmethod
def create_workers(cls, input_class, config):
workers = []
for input_data in input_class.generate_inputs(config):
workers.append(cls(input_data))
return workers
# newline 計數器
class LineCountWorker(GenericWorker):
def map(self):
data = self.input_data.read()
self.result = data.count("\n")
def reduce(self, other):
self.result += other.result
from threading import Thread
def execute(workers):
threads = [Thread(target=w.map) for w in workers]
for thread in threads: # 線程啟動
thread.start()
for thread in threads: # 等待所有線程結束
thread.join()
first, rest = workers[0], workers[1:]
for worker in rest: # 回收處理結果
first.reduce(worker)
return first.result
def mapreduce(worker_class, input_class, config):
workers = worker_class.create_workers(input_class, config)
return execute(workers)
config = {"data_dir": "/home/maomao/tmp"}
print("There are {} lines".format(mapreduce(LineCountWorker, PathInputData, config)))
There are 77 lines
class FatherClass(object):
def __init__(self, value):
self.value = value
class ChildClass(FatherClass):
def __init__(self, value):
FatherClass.__init__(self, value)
object1 = ChildClass(5)
print(object1.value)
5
class BaseClass(object):
def __init__(self, value):
self.value = value
class TimesTwo(object):
def __init__(self):
self.value *= 2
class PlusFive(object):
def __init__(self):
self.value += 5
class Order1(BaseClass, TimesTwo, PlusFive):
def __init__(self, value):
BaseClass.__init__(self, value)
TimesTwo.__init__(self)
PlusFive.__init__(self)
class Order2(BaseClass, PlusFive, TimesTwo):
def __init__(self, value):
BaseClass.__init__(self, value)
TimesTwo.__init__(self)
PlusFive.__init__(self)
object1 = Order1(2)
print(object1.value)
object2 = Order2(2)
print(object2.value)
9 9
class BaseClass(object):
def __init__(self, value):
self.value = value
class TimesTwo(BaseClass):
def __init__(self, value):
BaseClass.__init__(self, value)
self.value *= 2
class PlusFive(BaseClass):
def __init__(self, value):
BaseClass.__init__(self, value)
self.value += 5
class Order1(TimesTwo, PlusFive):
def __init__(self, value):
TimesTwo.__init__(self, value)
PlusFive.__init__(self, value)
class Order2(PlusFive, TimesTwo):
def __init__(self, value):
PlusFive.__init__(self, value)
TimesTwo.__init__(self, value)
object1 = Order1(2)
print(object1.value) # expect 9, but 7
object2 = Order2(2)
print(object2.value) # expect 14, but 4
7 4
class BaseClass(object):
def __init__(self, value):
self.value = value
class TimesTwo(BaseClass):
def __init__(self, value):
super(TimesTwo, self).__init__(value)
self.value *= 2
class PlusFive(BaseClass):
def __init__(self, value):
super(PlusFive, self).__init__(value)
self.value += 5
class Order1(TimesTwo, PlusFive):
def __init__(self, value):
super(Order1, self).__init__(value)
class Order2(PlusFive, TimesTwo):
def __init__(self, value):
super(Order2, self).__init__(value)
object1 = Order1(2)
print(object1.value) # expect 9, but 14
object2 = Order2(2)
print(object2.value) # expect 14, but 9
14 9
class Root(object):
def __init__(self):
print("Enter Root")
class A(Root):
def __init__(self):
print("Enter A")
super(A, self).__init__()
print("Leave A")
class B(Root):
def __init__(self):
print("Enter B")
super(B, self).__init__()
print("Leave B")
class C(Root):
def __init__(self):
print("Enter C")
super(C, self).__init__()
print("Leave C")
class Order1(A, B, C):
def __init__(self):
super(Order1, self).__init__()
print(Order1.mro())
object1 = Order1()
[<class '__main__.Order1'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.Root'>, <class 'object'>] Enter A Enter B Enter C Enter Root Leave C Leave B Leave A
class Order2(B, C, A):
def __init__(self):
super(Order2, self).__init__()
class Order3(C, A, B):
def __init__(self):
super(Order3, self).__init__()
print (Order2.mro())
object2 = Order2()
print()
print (Order3.mro())
object3 = Order3()
[<class '__main__.Order2'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class '__main__.Root'>, <class 'object'>] Enter B Enter C Enter A Enter Root Leave A Leave C Leave B [<class '__main__.Order3'>, <class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.Root'>, <class 'object'>] Enter C Enter A Enter B Enter Root Leave B Leave A Leave C
class BaseClass(object):
def __init__(self, value):
self.value = value
class TimesTwo(BaseClass):
def __init__(self, value):
super(TimesTwo, self).__init__(value)
self.value *= 2
class PlusFive(BaseClass):
def __init__(self, value):
super(PlusFive, self).__init__(value)
self.value += 5
class Order1(TimesTwo, PlusFive):
def __init__(self, value):
super(Order1, self).__init__(value)
print(Order1.mro())
object1 = Order1(2)
print(object1.value)
[<class '__main__.Order1'>, <class '__main__.TimesTwo'>, <class '__main__.PlusFive'>, <class '__main__.BaseClass'>, <class 'object'>] 14
class Order2(PlusFive, TimesTwo):
def __init__(self, value):
super(Order2, self).__init__(value)
print(Order2.mro())
object2 = Order2(2)
print(object2.value)
[<class '__main__.Order2'>, <class '__main__.PlusFive'>, <class '__main__.TimesTwo'>, <class '__main__.BaseClass'>, <class 'object'>] 9
__class__
, self).__init__
(value)__init__
(value)class BaseClass(object):
def __init__(self, value):
self.value = value
class TimesTwo(BaseClass):
def __init__(self, value):
super(__class__, self).__init__(value)
self.value *= 2
class PlusFive(BaseClass):
def __init__(self, value):
super().__init__(value)
self.value += 5
class Order1(TimesTwo, PlusFive):
def __init__(self, value):
super().__init__(value)
object1 = Order1(2)
print(object1.value)
14
__init__
class Fruit(object):
def __init__(self, cost):
self.cost = cost
class GiftMixin(object):
def is_sutible_gift(self):
return True
class NotGiftMixin(object):
def is_sutible_gift(self):
return False
class PareMixin(object):
def eat_method(self):
return "Pare"
class HuskMixin(object):
def eat_method(self):
return "Husk"
class Apple(Fruit, GiftMixin, HuskMixin):
def __init__(self, cost):
super().__init__(cost)
class Banana(Fruit, NotGiftMixin, PareMixin):
def __init__(self, cost):
super().__init__(cost)
apple = Apple(100)
banana = Banana(50)
print("Is apple a sutible gift?", apple.is_sutible_gift())
print("Is apple a sutible gift?", banana.is_sutible_gift())
print("How to eat apple?", apple.eat_method())
print("How to eat banana?", banana.eat_method())
Is apple a sutible gift? True Is apple a sutible gift? False How to eat apple? Husk How to eat banana? Pare
class ValueMixin(object):
def __getitem__(self, id):
return self.data[id]
def __setitem__(self, id, value):
self.data[id] = value
def __delitem__(self, id):
del self.data[id]
class CompareMixin(object):
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.__dict__ == other.__dict__)
def __ne__(self, other):
return not self.__eq__(other)
class SimpleItemContainer(ValueMixin, CompareMixin):
def __init__(self):
self.data = {}
object1 = SimpleItemContainer()
object1["aa"] = 111
object1["b"] = 2
print(object1["aa"], object1["b"])
print(object1.__dict__)
del object1["aa"]
print(object1.__dict__)
print()
object2 = SimpleItemContainer()
print("IS object1 equal object2?", object1 == object2)
print("IS object1 not equal object2?", object1 != object2)
object2["b"] = 2
print("IS object1 equal object2?", object1 == object2)
111 2 {'data': {'b': 2, 'aa': 111}} {'data': {'b': 2}} IS object1 equal object2? False IS object1 not equal object2? True IS object1 equal object2? True
# 無法直接透過物件存取私有屬性(可間接透過方法)
class Myobject(object):
def __init__(self):
self.public_field = 10
self.__private_field = 20
def get_private_field(self):
return self.__private_field
object1 = Myobject()
print(object1.public_field)
print(object1.get_private_field())
print(object1.__private_field)
10 20
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-84-45fb60191ae6> in <module>() 12 print(object1.get_private_field()) 13 ---> 14 print(object1.__private_field) AttributeError: 'Myobject' object has no attribute '__private_field'
# 子類別也無法存取父類別的私有屬性
class Father(object):
def __init__(self):
self.public_field = 10
self.__private_field = 20
class Child(Father):
def get_private_field(self):
return self.__private_field
object1 = Child()
print(object1.public_field)
print(object1.get_private_field())
10
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-88-0692c11e4b9f> in <module>() 11 print(object1.public_field) 12 ---> 13 print(object1.get_private_field()) <ipython-input-88-0692c11e4b9f> in get_private_field(self) 6 class Child(Father): 7 def get_private_field(self): ----> 8 return self.__private_field 9 10 object1 = Child() AttributeError: 'Child' object has no attribute '_Child__private_field'
# 類別方法(class method)可存取私有屬性,因為是定義在類別的區塊中
class Myobject(object):
def __init__(self):
self.public_field = 10
self.__private_field = 20
@classmethod
def get_private_field(cls, instance):
return instance.__private_field
object1 = Myobject()
print(object1.public_field)
print(Myobject.get_private_field(object1))
print(object1.__private_field)
10 20
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-273-6921a5bb26ca> in <module>() 15 print(Myobject.get_private_field(object1)) 16 ---> 17 print(object1.__private_field) AttributeError: 'Myobject' object has no attribute '__private_field'
# 無法直接透過物件存取私有屬性(可間接透過方法)
class Myobject(object):
public_field = 10
__private_field = 20
def get_private_field(self):
return self.__private_field
print(Myobject.public_field)
print(Myobject.__private_field)
10
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-104-94c55fa985c7> in <module>() 7 8 print(Myobject.public_field) ----> 9 print(Myobject.__private_field) AttributeError: type object 'Myobject' has no attribute '__private_field'
object1 = Myobject()
print(object1.public_field)
print(object1.get_private_field())
10 20
# [Bonus] 類別屬性&實體屬性
class Myobject(object):
public_field = 10
def set_public_field(self, number):
self.public_field = number
object1 = Myobject()
print("Class:", Myobject.public_field)
print("Instance:", object1.public_field)
object1.set_public_field(20)
print("#####################")
print("Class:", Myobject.public_field)
print("Instance:", object1.public_field)
Myobject.public_field = 30
print("#####################")
print("Class:", Myobject.public_field)
print("Instance:", object1.public_field)
object1.public_field = 40
print("#####################")
print("Class:", Myobject.public_field)
print("Instance:", object1.public_field)
Class: 10 Instance: 10 ##################### Class: 10 Instance: 20 ##################### Class: 30 Instance: 20 ##################### Class: 30 Instance: 40
class Myclass(object):
class_value = 5
def __init__(self):
self.instance_value = 10
def hello(self):
print("hello")
print(Myclass.__dict__)
print()
object1 = Myclass()
print(object1.__dict__)
{'__weakref__': <attribute '__weakref__' of 'Myclass' objects>, 'hello': <function Myclass.hello at 0x7f6bb9f74d08>, '__init__': <function Myclass.__init__ at 0x7f6bb9f74e18>, '__dict__': <attribute '__dict__' of 'Myclass' objects>, '__module__': '__main__', '__doc__': None, 'class_value': 5} {'instance_value': 10}
class Myclass(object):
"""doctstring for Myclass"""
class_value = 5
def __init__(self):
self.instance_value = 10
def hello(self):
print("hello")
print(Myclass.__dict__)
{'__weakref__': <attribute '__weakref__' of 'Myclass' objects>, 'hello': <function Myclass.hello at 0x7f6bb96246a8>, '__init__': <function Myclass.__init__ at 0x7f6bb9624730>, '__dict__': <attribute '__dict__' of 'Myclass' objects>, 'class_value': 5, '__module__': '__main__', '__doc__': 'doctstring for Myclass'}
class Myobject(object):
def __init__(self):
self.public_field = 10
self.__private_field = 20
def get_private_field(self):
return self.__private_field
object1 = Myobject()
print(object1.__dict__)
print()
print(object1._Myobject__private_field)
{'_Myobject__private_field': 20, 'public_field': 10} 20
class Father(object):
def __init__(self):
self.public_field = 10
self.__private_field = 20
class Child(Father):
def get_private_field(self):
return self._Father__private_field
object1 = Child()
print(object1.__dict__)
print()
print(object1.get_private_field())
print(object1._Father__private_field)
{'_Father__private_field': 20, 'public_field': 10} 20 20
class Myobject(object):
public_field = 10
__private_field = 20
def get_private_field(self):
return self.__private_field
print(Myobject.__dict__)
print()
print(Myobject._Myobject__private_field)
{'__weakref__': <attribute '__weakref__' of 'Myobject' objects>, '__dict__': <attribute '__dict__' of 'Myobject' objects>, '__module__': '__main__', 'public_field': 10, 'get_private_field': <function Myobject.get_private_field at 0x7f6bb9f14400>, '__doc__': None, '_Myobject__private_field': 20} 20
# 名稱同樣,但因為私有屬性的關係,使用上不衝突
class Father(object):
def __init__(self):
self.__myown_value = 10
def get_father_value(self):
return self.__myown_value
class Child(Father):
def __init__(self):
super().__init__()
self.__myown_value = 20
def get_child_value(self):
return self.__myown_value
object1 = Child()
print(object1.get_father_value())
print(object1.get_child_value())
print(object1.__dict__)
10 20 {'_Child__myown_value': 20, '_Father__myown_value': 10}
# 名稱同樣,但因為不是私有屬性的關係,使用上衝突
class Father(object):
def __init__(self):
self.myown_value = 10
def get_father_value(self):
return self.myown_value
class Child(Father):
def __init__(self):
super().__init__()
self.myown_value = 20
def get_child_value(self):
return self.myown_value
object1 = Child()
print(object1.get_father_value())
print(object1.get_child_value())
print(object1.__dict__)
20 20 {'myown_value': 20}
# 名稱同樣,但因為不是私有屬性的關係,使用上衝突
class Father(object):
def __init__(self):
self.myown_value = 10
def get_father_value(self):
return self.myown_value
class Child(Father):
def __init__(self):
self.myown_value = 20
super().__init__()
def get_child_value(self):
return self.myown_value
object1 = Child()
print(object1.get_father_value())
print(object1.get_child_value())
print(object1.__dict__)
10 10 {'myown_value': 10}
class Father(object):
def __init__(self, value):
# 儲存使用者提供的值
# 視為不可變變數
self._value = value
class Child(Father):
def __init__(self, value):
super().__init__(value)
def get_value(self):
return self._value
object1 = Child(100)
print(object1.get_value())
print(object1.__dict__)
100 {'_value': 100}
class SimpleList(list):
def __init__(self):
super().__init__()
object1 = SimpleList()
object1.append(1)
object1.append(2)
object1.append(3)
print(object1)
print(object1[0])
del object1[1]
print(object1)
[1, 2, 3] 1 [1, 3]
class FrequencyList(list):
def __init__(self, values):
super().__init__(values)
def frequency(self):
counts = {}
for i in self:
counts.setdefault(i, 0)
counts[i] += 1
return counts
object1 = FrequencyList(["a", "c", "b", "c", "e", "a"])
print("object1's length is", len(object1))
print("object1's frequency info is", object1.frequency())
object1.pop()
print("object1's length is", len(object1))
print("object1's frequency info is", object1.frequency())
object1's length is 6 object1's frequency info is {'b': 1, 'c': 2, 'a': 2, 'e': 1} object1's length is 5 object1's frequency info is {'b': 1, 'c': 2, 'a': 1, 'e': 1}
from collections.abc import Sequence
class BadType(Sequence):
pass
object1 = BadType()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-227-d27245bd6296> in <module>() 4 pass 5 ----> 6 object1 = BadType() TypeError: Can't instantiate abstract class BadType with abstract methods __getitem__, __len__
class BinaryNode(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class SequenceNode(BinaryNode, Sequence):
def __init__(self, value, left=None, right=None):
super().__init__(value, left, right)
self._BFS_resut = []
self._parse_tree()
# BFS
def _parse_tree(self):
self._BFS_resut.append(self.value)
search_list = [self]
while search_list:
current_node = search_list[0]
del search_list[0]
if current_node.left:
search_list.append(current_node.left)
self._BFS_resut.append(current_node.left.value)
if current_node.right:
search_list.append(current_node.right)
self._BFS_resut.append(current_node.right.value)
def __getitem__(self, index):
return self._BFS_resut[index]
def __len__(self):
return len(self._BFS_resut)
tree = SequenceNode(10, SequenceNode(5, SequenceNode(2)), SequenceNode(23, SequenceNode(9), SequenceNode(16)))
print(len(tree))
print(tree[4])
print([i for i in tree])
6 9 [10, 5, 23, 2, 9, 16]