Running Initializer For Class
Solution 1:
Here's a proof-of-concept of what I think you're trying to accomplish:
def Setting(value, description=None):
class Internal(type(value)):
def __new__(self, value, description=None):
return type(value).__new__(Internal, value)
def __init__(self, value, description=None):
super(Internal, self).__init__(value)
self.description = description
return Internal(value, description)
s = Setting(5, description="The maximum memory we can use")
print s+10, s.description
v = Setting([1, 2], description="A useful list")
print v+[3], v.description
which emits
15 The maximum memory we can use
[1, 2, 3] A useful list
The core idea is to wrap the class into a factory function -- an "extra level of indirectness" that should help you achieve your desired result.
I call this "a proof of concept", first of all, because it's quite wasteful of memory: a new class object springs up for every call to Setting
. The factory function should hold a dict
acting as a registry from type(value)
to the specific Internal
class wrapping it, populating it on the fly -- a typical "memoization" idiom, though here it's used to save memory, not so much running time.
Second, I haven't verified that all special methods behave as desired on a Setting
-wrapped "primitive type" (for all "primitive types" of interest, both mutable and immutable) -- offhand it seems like it should work, but nothing but thorough unit-testing can give you confidence here!-)
Solution 2:
The built-in repr()
of an object is a string. You can modify it with the repr
library, but I'm not sure it can be a different type. There are some additional details/ ideas in this SO question.
Solution 3:
If I understand you correctly, you want to have types/classes that behave normally like their type, and additionally have a 'description' field. How you go about it is strange - I believe the statement
type(value).__init__(value)
has no effect whatsoever, though I am perplexed why python doesn't throw a warning for this. Surely .init calls within an init should be reserved for super classes.
I would do the following and use s.value instead of s:
class Setting(object):
def __init__(self, value, description=None):
self.value = value
self.description = description
s = Setting(5)
print s.value + 5
print s.description
Post a Comment for "Running Initializer For Class"