A Quadcopter

quadcopter

Posted in Robotics

Python Dynamic Attribute Object

This is a simple dynamic attribute object in python.

class DynObject(object):
    """ Dynamic Attribute Object
    Usage:
        dynObj = DynObject()
        dynObj.attr = 'test'
        attr = dynObj.attr
        <Exception raised when accessing uninitialized attribute>
        attr = dynObj.attrNotInitialized
    Attributes:
        Dynamic Generated
    """
    
    def __init__(self):
        self._properties = {}
        pass
    
    def __getattr__(self, prop_name):
        _properties = object.__getattribute__(self, '_properties')
        if prop_name not in _properties.keys():
            raise AttributeError("Property not found %s" % (prop_name,))
        return _properties[prop_name]
    
    def has_attr(self, prop_name):
        """ Check if attribute defined
        Args: prop_name
        Returns: True if found
                 False if not found
        """
        return prop_name in self._properties
    
    def has(self, prop_name):
        """ Check if attribute defined, and value is not False
        Args: prop_name
        Returns: True if defined and True
                 False if not defined or defined but value is None/0/False
        """
        # Check exists and true (Not none)
        return True if self.has_attr(prop_name) and self._properties[prop_name] \
            else False
    
    def del_attr(self, prop_name):
        """ delete attribute
        Args: prop_name
        """
        del self._properties[prop_name]
        
    def __setattr__(self, prop_name, value):
        if prop_name == '_properties':
            object.__setattr__(self, '_properties', value)
        else:
            self._properties[prop_name] = value

    def __repr__(self):
        return self._properties.__str__()
# End class DynObject
Posted in Python

Recent Comments

    Archives

    Categories