Jared Henry Jared Henry - 3 months ago 22
Python Question

How Do I Build a Class with in a Class in Python

I am trying to model services and I am having some issue. What I am trying to do is I would want something such as this in code:

>>> service = Service()
>>> service.name = "Instance1"
>>> service.name.color = "red"
>>> service.name.color.enabled = True


I have tried nesting the Classes but I am still having issues.
Is this completely against convention. If so I will reevaluate and find another way to do so.

EDIT:
I decided to do something like the following by just nesting the classes to copy the Hierarchy.

class Service(object):
_prefix = 'Service'
def __init__(self):
self.name = Service.Name()
class Name(object):
_prefix = 'Service'
def __init__(self):
self.color = Service.Name.Color()
class Color(object):
_prefix = 'Service'
def __init__(self, color="N/A"):
self.color = color

Answer

You should be looking at composition, not nested classes.

class Color:
     def __init__(self, name):
         self.name = name

class Service:
     def __init__(self, color_obj):
         self.color_obj = color_obj

service = Service(Color("yellow"))
print(service.color_obj.name)
>> "yellow"