第17次全天课笔记 20181118 面向对象3
全天课笔记
"""写一个班级的类,存储班里人数,
统计班级里所有学科的最高分和平均分,
写班级里的学生类,存储学生所有成绩,
可以计算平均分和每个课程最高分"""
class Student(object):
def __init__(self,name,grade_class_no):
self.name = name
self.grade_class_no = grade_class_no
self.__chinese_score = None
self.__math_score = None
self.__english_score = None
def set_chinese_score(self,score):
if score >=0 and score<=100 and isinstance(score,(int,float)):
self.__chinese_score = score
else:
print("你输入的分数不是数字类型,或者不在0-100分数的范围内!")
def get_chinese_score(self):
return self.__chinese_score
def set_math_score(self,score):
if score >=0 and score<=100 and isinstance(score,(int,float)):
self.__math_score = score
else:
print("你输入的分数不是数字类型,或者不在0-100分数的范围内!")
def get_math_score(self):
return self.__math_score
def set_english_score(self,score):
if score >=0 and score<=100 and isinstance(score,(int,float)):
self.__english_score = score
else:
print("你输入的分数不是数字类型,或者不在0-100分数的范围内!")
def get_english_score(self):
return self.__english_score
def get_max_score(self):
return max(self.__chinese_score,self.__math_score,self.__english_score)
def get_avg_score(self):
return sum([self.__chinese_score,self.__math_score,self.__english_score])/3
def get_total_score(self):
return sum([self.__chinese_score,self.__math_score,self.__english_score])
class Class_NO(object):
"""管理班级数据的类"""
def __init__(self,name):
self.grade_class_name = name
self.students = []
def set_grade_class_name(self,name):
self.grade_class_name = name
def get_grade_class_name(self):
return self.grade_class_name
def add_student(self,student):
self.students.append(student)
def get_max_total_score(self):
student_total_score=[]
for i in self.students:
student_total_score.append(i.get_total_score())
return max(student_total_score)
def get_avg_score(self):
student_total_score=[]
for i in self.students:
student_total_score.append(i.get_total_score())
return sum(student_total_score)/len(self.students)
if __name__ == "__main__":
s = Student("张三","三年级二班")
s.set_chinese_score(100)
s.set_math_score(80)
s.set_english_score(60)
t = Student("李四","三年级二班")
t.set_chinese_score(100)
t.set_math_score(50)
t.set_english_score(10)
c= Class_NO("三年级二班")
c.add_student(s)
c.add_student(t)
print(c.get_max_total_score())
print(c.get_avg_score())
>>> class P:
... def __init__(self):
... self.name ="a"
... self.class_name="b"
...
>>> p=P()
>>> hasattr(p,"name")
True
>>> hasattr(p,"class")
False
>>> getattr(p,"name")
'a'
>>> delattr(p,"name")
>>> hasattr(p,"name")
False
>>>
单例 只能生成一个实例
class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kw)
return cls._instance
class MyClass(Singleton):
a = 1
one = MyClass()
two = MyClass()
two.a = 3
print (one.a)
#3
#one和two完全相同,可以用id(), ==, is检测
print (id(one))
#29097904
print (id(two))
#29097904
print (one == two)
#True
print (one is two)
#True
Python对象销毁(垃圾回收)
当没有被引用时,会被垃圾回收
当对象被创建时,就创建了一个引用计数,当这个对象不再需要时,
也就是说,这个对象的引用计数变为0 时,它被垃圾回收。
Linux
缓存文件和目录信息,实际可用是 free+bufffers+cached
循环引用的对象被销毁
class LeakTest:
def __init__(self):
self.a = None
self.b = None
print ("object = %d born here." % id(self))
A = LeakTest()
B = LeakTest()
A.a = B
B.b = A
import sys
print (sys.getrefcount(A))
print (sys.getrefcount(B))
del A
try:
print (sys.getrefcount(A))
except Exception as e:
print (e)
del B
try:
print (sys.getrefcount(B))
except Exception as e:
print (e)
python装饰器(Decorator)
为函数提供一些通用的功能
变量相关-作用域
#coding=utf-8
outerVar = "this is a global variable"
def test() :
innerVar = "this is a Local variable"
print ("local variables :")
print (locals())
test()
print ("global variables :")
print (globals())
锻炼
读书 三体
时间管理- 一天的管理
自己的成长- 长期,短期,中期的时间管理
做好计划,降低干扰,让自己更专注,长期目标离目标更接近
闭包
def outer(name) :
name1="hi"
def inner() :
print (name)
print (name1)
return inner
res1 = outer("python")
print(res1. __closure__)
res2 = outer("java")
res1()
res2()
装饰器的好处:能够给所有的函数增加一下附加的功能
#装饰器的好处:能够给所有的函数增加一下附加的功能。
本质就是,@deco是个装饰函数函数,他需要返回一个闭包。
闭包由_deco函数对象+原函数对象(闭包变量)。
_deco函数对象本质:执行了附加的功能,并且执行了原函数。
import time
def deco(func):
def _deco():
print ("before myfunc() called.")
time1=time.time()
func()
time.sleep(2)
time2=time.time()
print (" after myfunc() called.")
print("%s函数执行耗时:%s" %(func.__name__,time2-time1))
# 不需要返回func,实际上应返回原函数的返回值
return _deco
@deco
def myfunc(): # 等价于闭包:_deco()+ myfunc
print (" myfunc() called.")
myfunc() #等价于闭包:_deco()+ myfunc