propjk007 propjk007 -3 years ago 114
Python Question

Python - Using a class to enable dot notation

Working on a class that has sub properties. Is the below code a good practice / Pythonic? If not, have any suggestion?


exp = ExCls()
prop1 = exp.subprop.prop1
## prop1 = 1
## prints 2


class ExCls():
class subprop:
prop1 = 1
prop2 = 2
def print_prop2(self):
print self.subprop.prop2

Answer Source

In most of the common higher level languages, dot notation is used to indicate namespace. The same is true for Python. Take the following useless class for example:

>>> class UselessClass(object):
...     @property
...     def and_on(self):
...         return self
...     def forever(self):
...         return "I can see into forever"
>>> this_goes_on = UselessClass()
>>> this_goes_on.and_on.and_on.and_on.and_on.and_on.forever()
'I can see into forever'

All it's doing is returning itself (an instantiated object of type UselessClass), which has access to all of it's own properties.

The only issue with your code is, as GingerPlusPlus pointed out, you're making subprop shared between all instances of ExCls. This may be desired, but (based on the question), also may not be. Here's an instance of why this is bad:

>>> test1 = ExCls()
>>> test2 = ExCls()
>>> test1.subprop.prop1
>>> test2.subprop.prop1 = 2
>>> test1.subprop.prop1

As you can see, this isn't generally the behaviour you'd expect. Instead, what you may be looking to do is:

class ExCls(object):
    def __init__(self):
        class subprop:
            prop1 = 1
            prop2 = 2
        self.subprop = subprop()

    def print_prop2(self):

Overall, I'd highly recommend going back and reading up on Python's Classes, and how they work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download