要从中继承的一组有用的python类

predecessor的Python项目详细描述


概述

这组库旨在提供有用的类来继承 以一种跨语言兼容的方式。一个 此库的版本当前位于:

  • Python(2或3)
  • javascript

当前提供的库:

  • 单例对象
  • 可序列化对象

单重态

singleton类提供了一种方法来确保只有一个实例 属于一个阶级。例如:

frompredecessorimportSingletonclassExample(Singleton):def__init__(self,foo,bar):self.foo=fooself.bar=bara=Example(3,8)b=Example(2,9)aisb# returns Truea.foo==b.foo==3# returns True

或者在javascript中等效:

constSingleton=require('predecessor').Singleton;classExampleextendsSingleton{constructor(foo,bar){this.foo=foo;this.bar=bar;}}leta=newExample(3,8);letb=newExample(2,9);a===b;// returns true
a.foo===3;// returns true
b.foo===3;// returns true

可串行化

singleton类提供了一种无需序列化类的方法 关心结果blob的形式如果兼容类 定义在所有支持的语言中都可用,它应该是 可在所有支持的语言中反序列化。

基本情况

frompredecessorimportSerializableclassExample(Serializable):def__init__(self,foo,bar):# Note that keyword args are not supportedself.foo=fooself.bar=bardefserialized(self):returnsuper(Example,self).serialized(self.foo,self.bar)a=Example(3,8)b=Example.deserialize(a.serialized())a.foo==b.foo==3# returns Truea.bar==b.bar==8# returns True

或者在javascript中等效:

constSerializable=require('predecessor').Serializable;classExampleextendsSerializable{constructor(foo,bar){this.foo=foo;this.bar=bar;}serialized(){returnsuper.serialized(this.foo,this.bar);}}leta=newExample(3,8);letb=Example.deserialize(a.serialized());a.foo===3;// returns true
b.foo===3;// returns true
a.foo===8;// returns true
b.foo===8;// returns true

隐含序列化

在这两种语言中,还可以使用隐含序列化。这看起来 例如:

classExample(Serializable):__slots__=('a','b','c')def__init__(self,a,b,c):self.a=aself.b=bself.c=c
classExampleextendsSerializable{constructor(a,b,c){super();this._slots=['a','b','c'];this.a=a;this.b=b;this.c=c;}}

高级重组

在这两种语言中,您可以在将数据输入 你的构造器

classExample(Serializable):def__init__(self,a,b,c):self.a=aself.b=bself.c=cdefserialized(self):returnsuper(Example,self).serialized(self.a,self.b)@classmethoddefrecombine(cls,a,b):returncls(a,b,a+b)
classExampleextendsSerializable{constructor(a,b,c){super();this.a=a;this.b=b;this.c=c;}serialized(){returnsuper.serialized(this.a,this.b);}staticrecombine(a,b){returnnewthis(a,b,a+b);}}

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java OpenShift的齿轮特性   java如何在Liferay站点的每个页面上放置公司地址和电话?   java确定整数数组中是否存在一个子集,在两个条件下求和到给定的目标值   序列化为什么java中的serialVersionUID必须是静态的、最终的、长类型的?   java响应返回null   java注入接口实现Quarkus   java我不明白为什么第二次排序的运行时间比第一次慢?   (Java)显示图像的最佳方式?   java Android应用程序因添加布局而崩溃   java如何在运行时获取泛型变量的类   java Selenium web驱动程序:无效的选择器:*:WebKitFullScreenSentor   Spring中的java注入值始终为空   Eclipse中带有TestNG插件的@BeforeSuite和@AfterSuite的java问题   使用trycatch块、filewriter和printwriter在java中创建自定义类   如何在Java 安卓上绘制相交的两条线