习题:

1. Shape基类,要求所有子类都必须提供面积的计算,子类有三角形、矩形、圆。

2. 上题圆类的数据可序列化

第一种方法:使用Mixin多继承组合的方式,混入其它类的属性和方法

第二种方法:使用装饰器装饰类,动态添加属性和方法

实例:

import math
import json
import msgpack
import pickle class Shape:
"""防止直接调用父类的area方法"""
@property
def area(self):
raise NotImplementedError('基类未实现') class Triangle(Shape):
"""三角形"""
def __init__(self,a,b,c):
self.a = a
self.b = b
self.c = c @property
def area(self):
p = (self.a+self.b+self.c)/2
return math.sqrt(p*(p-self.a)*(p-self.b)*(p-self.c)) class Rectangle(Shape):
"""矩形"""
def __init__(self,width,height):
self.width = width
self.height = height @property
def area(self):
return self.width * self.height def SerializableCircle(cls):
""" 1.装饰器为类动态添加dumps方法"""
# print(cls)
def dumps(self,t='json'):
if t == 'json':
return json.dumps(self.__dict__)
elif t == 'msgpack':
return msgpack.packb(self.__dict__)
elif t == 'pickle':
with open('dump.txt','wb') as f:
return pickle.dump(self.__dict__,f)
else:
raise NotImplementedError('没有实现的序列化') cls.dumps = dumps
return cls @SerializableCircle # Circle=SerializableCircle(Circle)
class Circle(Shape):
"""圆形"""
def __init__(self,radius):
self.radius = radius @property
def area(self):
return (self.radius ** 2) * math.pi # def dumps(self,t='json'):
# if t == 'json':
# return json.dumps(self.__dict__)
# elif t == 'msgpack':
# return msgpack.packb(self.__dict__)
# elif t == 'pickle':
# with open('dump.txt','wb') as f:
# return pickle.dump(self.__dict__,f)
# else:
# raise NotImplementedError('没有实现的序列化') # sc = Circle(4)
# sc.dumps('pickle') class SerializableMixin:
"""序列化"""
def dumps(self,t='json'):
if t == 'json':
return json.dumps(self.__dict__)
elif t == 'msgpack':
return msgpack.packb(self.__dict__)
elif t == 'pickle':
with open('dump.txt','wb') as f:
return pickle.dump(self.__dict__,f)
else:
raise NotImplementedError('没有实现的序列化') def loads(self,t='json'):
pass class SerializableCircleMixin(SerializableMixin,Circle):
""" 2.Mixin组合为类动态添加dumps方法"""
pass shapes = [Triangle(3,4,5), Rectangle(3,4), Circle(4)]
for s in shapes:
print('The area of {} = {}'.format(s.__class__.__name__,s.area)) #Mixin
scm = SerializableCircleMixin(4)
print(scm.area)
s = scm.dumps('msgpack')
print(s) #装饰器
sc = Circle(4)
s = sc.dumps('json')
print(s)

  

Python 动态添加类方法的更多相关文章

  1. python动态添加属性和方法

    ---恢复内容开始--- python动态添加属性: class Person(object): def __init__(self,newName,newAge): self.name = newN ...

  2. python 动态添加属性及方法及“__slots__的作用”

    1.动态添加属性 class Person(object): def __init__(self, newName, newAge): self.name = newName self.age = n ...

  3. python动态添加属性

    class A: def __init__(self, info ={}): self.info = info def __getattr__(self, item): return self.inf ...

  4. 我的Python学习笔记(四):动态添加属性和方法

    一.动态语言与静态语言 1.1 动态语言 在运行时代码可以根据某些条件改变自身结构 可以在运行时引进新的函数.对象.甚至代码,可以删除已有的函数等其他结构上的变化 常见的动态语言:Object-C.C ...

  5. day_5.26python动态添加属性和方法

    python动态添加属性和方法 既然给类添加⽅法,是使⽤ 类名.⽅法名 = xxxx ,那么给对象添加⼀个⽅法 也是类似的 对象.⽅法名 = xxx '''2018-5-26 13:40:09pyth ...

  6. 20170702-变量说明,静态方法,类方法区别,断点调试,fork,yield协程,进程,动态添加属性等。。

    概念: 并行:同时运行 并发:看似同时运行  json后任然中文的问题 import json d = {"名字":"初恋这件小事"} new_d1 = jso ...

  7. 细说python类2——类动态添加方法和slots(转)

    先说一下类添加属性方法和实例添加属性和方法的区别, 类添加属性属于加了一个以类为全局的属性(据说叫静态属性),那么以后类的每一个实例化,都具有这个属性.给类加一个方法也如此,以后类的每一个实例化都具备 ...

  8. Python __slots__限制动态添加变量

    Python是一种非常灵活的动态语言,有时感觉太灵活以至于不知道遵循什么样的规则去驾驭.不过Python已经是非常完备的语言,想实现什么样的功能都是有方法的,而且也很容易,比如限制一个类动态添加成员变 ...

  9. 第六种方式,python使用cached_property缓存装饰器和自定义cached_class_property装饰器,动态添加类属性(三),selnium webdriver类无限实例化控制成单浏览器。

    使用 from lazy_object_proxy.utils import cached_property,使用这个装饰器. 由于官方的行数比较少,所以可以直接复制出来用自己的. class cac ...

随机推荐

  1. win10 UWP 标签

    本文主要翻译:http://visuallylocated.com/post/2015/02/20/Creating-a-WrapPanel-for-your-Windows-Runtime-apps ...

  2. Software development process

    一.Development process 1.Business/User Requirement 2.Architecture Proposal,Solution Proposal 3.Functi ...

  3. VIM文本替换命令

    在VIM中进行文本替换:       1.  替换当前行中的内容:    :s/from/to/    (s即substitude)         :s/from/to/     :  将当前行中的 ...

  4. Akka(30): Http:High-Level-Api,Routing DSL

    在上篇我们介绍了Akka-http Low-Level-Api.实际上这个Api提供了Server对进来的Http-requests进行处理及反应的自定义Flow或者转换函数的接入界面.我们看看下面官 ...

  5. SGU 223 Little Kings(状压DP)

    Description 用字符矩阵来表示一个8x8的棋盘,'.'表示是空格,'P'表示人质,'K'表示骑士.每一步,骑士可以移动到他周围的8个方格中的任意一格.如果你移动到的格子中有人质(即'P'), ...

  6. JS的简单用法

    JS的简单用法 参考:http://www.w3school.com.cn/js/js_switch.asp JavaScript 是网络的脚本语言 JavaScript 是可插入 HTML 页面的编 ...

  7. PHPExcel-1.8导出

    //PHPExcel-1.8导出excel<?phpheader("Content-type: text/html; charset=utf-8");mysql_query( ...

  8. 版本12.2.0.1.0数据库,复制种子数据库快速创建租户数据库PDB

    实验测试:快速创建一个数据库PDB2: 实验环境:12.2.0.1.0版本数据库,dbca图形化安装,现有环境,CDB容器数据库ORCL,PDB可插拔数据库ABC   ---查询CDB名称,状态 SQ ...

  9. HDU4027 Can you answer these queries?(线段树 单点修改)

    A lot of battleships of evil are arranged in a line before the battle. Our commander decides to use ...

  10. Milking Time

    Description Bessie is such a hard-working cow. In fact, she is so focused on maximizing her producti ...