Created
December 17, 2014 14:54
-
-
Save pzwang/3ec8fb0d2cd66d2d493f to your computer and use it in GitHub Desktop.
Exercise 7.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Structure(object): | |
_fields = [] | |
def __init__(self, *args, **kw): | |
""" Generic constructor which initializes the object with the passed- | |
in values, based on positional order and name in the **_fields** | |
class variable. Subclasses need to define **_fields** appropriately. | |
""" | |
remaining_fields = self._fields[:] | |
if len(args) > 0: | |
if len(args) > len(self._fields): | |
raise RuntimeError("Too many arguments; expected %d, got %d" % \ | |
len(self._fields), len(args)) | |
for name, val in zip(self._fields, args): | |
setattr(self, name, val) | |
remaining_fields = self._fields[len(args):] | |
if len(remaining_fields) > 0: | |
for key, val in kw.iteritems(): | |
if key in remaining_fields: | |
setattr(self, key, val) | |
elif key in self._fields: | |
raise RuntimeError("Duplicate values provided for field '%s'" % key) | |
else: | |
raise RuntimeError("Unknown field '%s'" % key) | |
class Test(Structure): | |
_fields = ["a", "b", "c"] | |
def printself(self): | |
print self.__dict__ | |
t = Test() | |
print "[t]", | |
t.printself() | |
t2 = Test(10, 20, 30) | |
print "[t2]", | |
t2.printself() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment