Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Llabel demo class for constructing class objects with different constructors and exporting them in different ways
#!/usr/bin/env python
# -*- coding: utf8 -*-
class Llabel(object):
"""
Lfunction Label
---------------
Description of D, deltas, ...
"""
def __init__(self, D, deltas, N, chi, mu):
"""
Main Constructor
"""
# TODO: add validation for each argument
self.D = D
self.deltas = deltas
self.N = N
self.chi = chi
self.mu = mu
@classmethod
def from_string(klass, s):
"""
parses the string @s and returns the Llabel object
"""
# this is only a DEMO!!!
D = s[:3]
deltas = map(float, s[3:10].split("_"))
N = 1
chi = 2
mu = [1.1, 1.5, 2]
# and more
return klass(D, deltas, N, chi, mu)
@classmethod
def from_url(klass, u):
"""
"""
ul = u.split("/")
raise Exception("NYI")
@classmethod
def from_dblabel(klass, l):
"""
uses l to construct the class
"""
D, deltas, N, chi, mu = l
return klass(D, deltas, N, chi, mu)
def to_string(self):
"""
converts the internal state to the string representation
"""
deltas = '_'.join(map(str, self.deltas))
mu = '_'.join(map(str, self.mu))
return '__'.join(map(str, [self.D, deltas, self.N, self.chi, mu]))
def to_url(self):
"""
...
"""
deltas = '_'.join(map(str, self.deltas))
mu = '_'.join(map(str, self.mu))
return '/'.join(map(str, [self.D, deltas, self.N, self.chi, mu]))
def to_dblabel(self):
return [self.D, self.deltas, self.N, self.chi, self.mu]
def __str__(self):
"""
canonical string
"""
return 'Llabel: %s' % self.to_url()
if __name__ == '__main__':
print "creating one"
l1 = Llabel(22, [1.5, -1], 1, 2, [1.1, 2.123, -1, 5])
print 'as string:', l1.to_string()
print 'as db_label:', l1.to_dblabel()
print 'and as url:', l1.to_url()
print
print "from a label to the Llabel object"
l1_db = l1.to_dblabel()
print l1_db
print type(l1_db)
print
l_new = Llabel.from_dblabel(l1_db)
print l_new # calls __str__
print type(l_new)
print
print "the old D is = %s" % l1.D
print "the new D is = %s" % l_new.D
# are they equal -> that's a test ;-)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.