PMembrey
asked on
Metaclass to create custom object in Python
Hi,
I'd like to create a class that has two dictionaries, each name for one of the arguments passed to __init__(). For example:
a = new Foo(school,children)
a.school and a.children would be empty dictionaries.
Is that easy enough to do?
I'd like to create a class that has two dictionaries, each name for one of the arguments passed to __init__(). For example:
a = new Foo(school,children)
a.school and a.children would be empty dictionaries.
Is that easy enough to do?
ASKER
Hi cho7,
The object is supposed to have two dictionaries in it.
That's the whole point :-)
The object is supposed to have two dictionaries in it.
That's the whole point :-)
It's the same thing, just replace -1 by {} (see snippet)
When I'm saying "consider using dictionnaries", it's because what you want to do is not very python-like
see snippet too :)
When I'm saying "consider using dictionnaries", it's because what you want to do is not very python-like
see snippet too :)
class Meta:
def __init__(self,a,b):
exec "self.%s={}"%(a)
exec "self.%s={}"%(b)
a = Meta("x","y")
print "a.x = ",a.x
print "a.y = ",a.y
#What I think you should do :
class MetaMadeInPython:
def __init__(self,a,b):
self._data = {}
self._data[a] = {}
self._data[b] = {}
def __getitem__(self,index):
return self._data[index]
b = MetaMadeInPython("x","y")
print "b.x = ", b["x"]
print "b.y = ", b["y"]
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
This does exactly what I want :)
otherwise a = Foo(school,children) will not work ! (and yes, there's no [new] operator in python to instanciate object !
You will have to call it like this :
a = Foo ("school","children")
See snippet to an example, but it's ugly. You should consider using dictionnaries !
Open in new window