How can I access methods of a class that is passed as argument to another class in python

74 Views Asked by At

I want to create a class(say, LockedAttributes) to access(READ/WRITE) some attributes safely by multiple threads.I want to pass those attributes that I want to share as a list to the LockedAttributes class. Some of the list elements are itself class objects with it's own setter and getter. How can i access those setter/getter from a LockedAttribute class obj? My use of getattr() setattr() might be wrong. sample code:

class Coord:

def __init__(self, x=0.0, y=0.0, z=0.0):
    self.x = x
    self.y = y
    self.z = z

def set_coordinator(self, x, y, z):
    self.x = x
    self.y = y
    self.z = z

def get_coordinator(self):
    return self.x, self.y, self.z

class LockedAttributes(object):
def __init__(self, obj):
    self.__obj = obj
    self.__lock = RLock()

def getmyPosition(self):
    with self.__lock:
        return self.__obj[0]

def getmySpeed(self):
    with self.__lock:
        return self.__obj[1]

def getcolPosition(self):
    with self.__lock:
        return self.__obj[2]
def getDistfromCol(self):
    with self.__lock:
        getattr(self, self.__obj[3]) 
def setDistfromCol(self, value):
    with self.__lock:
        setattr(self, self.__obj[3], value) 
def getcolactivationFlag(self):
    with self.__lock:
        getattr(self, self.__obj[4])

def setcolactivationFlag(self, value):
    with self.__lock:
        setattr(self, self.__obj[3], value)


class OBU():
def __init__(self):     
   pos = Coord()
  speed = Coord()
  colpos = Coord()
  distance_from_accident = 0.0
  Flag = False
  self.shared_attributes = LockedAttributes([ pos, speed, colpos, distance_from_accident, Flag])

  mypos= self.shared_attributes.getmyPosition()
  mypos.get_coordinator() # Not workinh
1

There are 1 best solutions below

7
blhsing On BEST ANSWER

The __init__ method of the LockedAttributes class should take an argument so that you can actually pass a list object to it.

Change:

class LockedAttributes(object):
    def __init__(self):
        self.__obj = object
        self.__lock = RLock()

To:

class LockedAttributes(object):
    def __init__(self, obj):
        self.__obj = obj
        self.__lock = RLock()