how to create nested classes dynamically

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Nov 4 00:55:00 EST 2009


En Wed, 04 Nov 2009 02:04:11 -0300, gopal mishra <gopalm at infotechsw.com>  
escribió:

> I have class structure as below. How can I create the following nested  
> class
> and its properties dynamically.
>
>
> class AA(object):
>
>     class BB(object):
>
>         def setBB1(self, value):
>
>             ##some code
>
>         def getBB1(self):
>
>             bb1 = #somecode
>
>             return bb1
>
>         bb1 = property(getBB1, setBB1, None, None)
>
>         bb2 = ...
>
>     bb = BB()
>
>     class CC(object):
>
>         ....
>
>     cc = CC()
>
> aa = AA()

First, I assume getBB1 and setBB1 really do some actual work. If they're  
just accessors for an instance attribute, don't use them; don't write Java  
in Python [1]

In Python, you may have instance (or "normal") attributes, and class  
attributes. When you say obj.name, if name is not found as an instance  
attribute, it is looked up on its class (and all its base classes; this is  
how methods are searched, BTW)
Class attributes are "shared" among all instances - that is, all instances  
retrieve the same object when you access a class attribute.

Your code above, as it is written, creates two class attributes named bb  
and cc (they're class attributes because the statements bb=... and cc=...  
are inside the class definition). It works, but perhaps that's not what  
you want. If you want instance attributes instead, create them in  
AA.__init__ by using self.bb=something

Nested classes provide no benefit here and are harder to use, so just move  
the class definitions to the module level. The code would become:

class BB(object):
   def setBB1(self, value):
     ##some code

   def getBB1(self):
     "docstring for the property"
     bb1 = #somecode
     return bb1

   bb1 = property(getBB1, setBB1)
   bb2 = ...


class CC(object):
   ....

class AA(object):
   def __init__(self, ...):
     self.bb = BB()
     self.cc = CC()

Then, you can write:

aa = AA()
print aa.bb.bb1
aa.bb.bb2 = '10'
print aa.bb.bb2

[1] http://dirtsimple.org/2004/12/python-is-not-java.html

-- 
Gabriel Genellina




More information about the Python-list mailing list