如何访问作为参数传递给 python 中另一个 class 的 class 的方法

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

我想创建一个 class(例如,LockedAttributes)来通过多个安全地访问(READ/WRITE)一些属性 threads.I 想传递那些我想共享的属性LockedAttributes class 的列表。一些列表元素本身就是 class 个对象,具有自己的 setter 和 getter。 我如何从 LockedAttribute class obj 访问那些 setter/getter? 我对 getattr() setattr() 的使用可能是错误的。 示例代码:

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

LockedAttributes class 的 __init__ 方法应该有一个参数,这样你就可以实际传递一个列表对象给它。

变化:

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

收件人:

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