要从中继承的一组有用的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);}}