Skip to content Skip to sidebar Skip to footer

How To Set A Variable's Subproperty?

I am a newbie to Python. I got some Python sample code from a software vendor who extended their software API with boost.python so we can call them in Python. I am confused with so

Solution 1:

I don't really see what's the issue. Consider an Enum defined in python:

import enum


class Type(enum.Enum):
    Bird = 0
    Cat = 1

The Type.Bird and Type.Cat are instances of the Type class:

>>> Type.Bird
<Type.Bird: 0>
>>> Type.Cat
<Type.Cat: 1>

As such they have access to their own class, which is Type:

>>> Type.Bird.__class__
<enum 'Type'>

Now you can just add a property to the Type class and obtain that behaviour:

class Type(enum.Enum):
    Bird = 0
    Cat = 1

    @property
    def enum(self):
        return self.__class__

and now you have:

>>> Type.Bird
<Type.Bird: 0>
>>> Type.Bird.enum
<enum 'Type'>
>>> Type.Bird.enum.Bird
<Type.Bird: 0>
>>> Type.Bird.enum.Cat
<Type.Cat: 1>

Note that while the above allows you to write Bird.enum doesn't allow you to access as in Type.enum because this would return the property object.

To obtain the exact behaviour you see in that code you could:

  • Set the settings.Type attribute to be an instance of Type (possibly an Invalid one) and be done:

    def AddAnimalSettings(*args)
        settings = MyClass(*args)
        settings.Type = Type.Bird
        return settings
    
  • Replace the use of property with a custom made descriptor that will handle the access via the class too. In this case read the documentation about property which also provides its python code equivalent. The case you have to change is __get__ when obj is None:

    class MyProperty(object):
    
        # omissis
    
        def __get__(self, obj, objtype=None):
            if obj is None:
                return objtype   # <-- changed this line
            if self.fget is None:
                raise AttributeError("unreadable attribute")
            return self.fget(obj)
    

    Use this as:

    class Type(enum.Enum):
        Bird = 0
        Cat = 1
    
        @MyProperty
        def enum(self):
            return self.__class__
    

    And now you have:

    >>> Type.enum
    <enum 'Type'>
    

    so that Type.enum.Bird works.


Post a Comment for "How To Set A Variable's Subproperty?"