【问题标题】:How can I access methods of a class that is passed as argument to another class in python如何访问作为参数传递给python中另一个类的类的方法
【发布时间】:2019-07-21 13:51:42
【问题描述】:

我想创建一个类(例如,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

【问题讨论】:

    标签: multithreading python-2.7 parameter-passing shared-variable list-processing


    【解决方案1】:

    LockedAttributes 类的__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()
    

    【讨论】:

    • 我已经编辑了我的代码。但问题仍然存在。似乎 getmyPosition() 没有返回 Coord() 对象,我不能使用 setter/getter。一个问题,即使当我能够通过 getmyPosition 以安全的方式访问位置对象时,我仍将使用 Coord 类自己的方法来读取/写入它的值。那也是线程安全的吗?
    • 是的,这样做是线程安全的,因为锁会阻止其他线程同时进入 getter/setter,从而阻止它们进一步进入 Coord 的方法。跨度>
    • 谢谢!但是, getmyPosition() 没有返回列表的第一个元素。这是 pos 对象。你知道为什么吗?
    • 它肯定可以工作。请运行演示:repl.it/repls/WelltodoMotherlyProcesses
    • 很高兴知道。通过with 语句将锁用作上下文管理器,它会在离开with 块时为您释放锁,因此您不必担心手动释放它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2014-08-26
    • 2012-10-18
    • 2023-01-18
    相关资源
    最近更新 更多