我想创建一个类(比如,LockedAttributes)来安全地访问(读/写)多个线程的一些属性。我想将那些我想要作为列表共享的属性传递给LockedAttributes类。一些列表元素本身就是类对象,它有自己的setter和getter。如何从LockedAttribute类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
__init__
类的LockedAttributes
方法应该采用一个参数,以便您可以实际传递一个列表对象。
更改:
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()