Avatar of PMembrey
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?
Python

Avatar of undefined
Last Comment
PMembrey

8/22/2022 - Mon
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

PMembrey

ASKER
Hi cho7,

The object is supposed to have two dictionaries in it.

That's the whole point :-)
cho7

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

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
mish33

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
PMembrey

ASKER
This does exactly what I want :)