Link to home
Start Free TrialLog in
Avatar of PMembrey

asked on

Metaclass to create custom object in Python


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) and a.children would be empty dictionaries.

Is that easy enough to do?
Avatar of cho7

is there something in school and children ?

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 !

class Meta:
    def __init__(self,a,b):
        exec "self.%s=-1"%(a)
        exec "self.%s=1"%(b)

a = Meta("x","y")

print "a.x = ",a.x
print "a.y = ",a.y

Open in new window

Avatar of PMembrey


Hi cho7,

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 :)

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"]

Open in new window

Avatar of mish33
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This does exactly what I want :)