我想创建一个类(例如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
答案 0 :(得分:0)
__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()