Python Tip: Properties with a parameter
This is probably”unpython” and whatever, but I do a lot of automation, and being able to access properties based on some index (like a port number) is pretty important. This is especially true since getting a property isn’t reading a variable, it’s actually reading the value from some piece of equipment.
And, in case pastebin dissapears:
# This was created based on a response from Alex Martelli at:
# http://bytes.com/topic/python/answers/35919-property-parameter#post133951
# There’s probably a way to do this with an object (without the .property)
class ParameterProperty(object):
# Allows using a property with a parameter, such as
# portSpeed[3] = 1000
# print portSpeed[3]
def __init__(self,getparam,setparam):
# Initialize by specifying the getter and setter functions.
self.getparam = getparam
self.setparam = setparam
def getPropertyAccessor(self):
# create a class with get and set
class PropertyArrayAccessor: pass # class to return
def getter(__, parameter): # create getter function
return self.getparam(parameter) # return the value from the function specified during init
def setter(__, parameter, value): # create setter function
self.setparam(parameter,value) # call the function specified during init
# property will use these get and set functions
PropertyArrayAccessor.__getitem__ = getter
PropertyArrayAccessor.__setitem__ = setter
return PropertyArrayAccessor() # return the class object
property
