pythonic 如何创建对自己的 python class 实例的引用并使用它?

How is the pythonic way to create a reference to a own python class instance and use it?

我想将 class 的实例存储在像列表这样的容器中。其他 classes/methods 应该访问此实例。

下面是定义数据点的代码片段。

class dataPoint(object):
    def __init__(self, name, typeUUID, value = None):
        self.name = name
        self.typeUUID = typeUUID
        self.value = value

我喜欢定义一个方法,该方法为我提供对该对象的引用(无复制构造函数等)。可能是这样的:

def getRef(self):
    return ???

我喜欢在不同的列表中使用这些参考资料。我喜欢用来设置数据点的 properties/call 函数的参考。下面是一些伪代码:

# define a conatiner with datapoints    
myContainer = [dataPoint("temperature","double",273.15), dataPoint("power","double",230), dataPoint("errorcode","uint32",666)]

# define interfaces which refers to the datapoints
interface1 = [ref("temperature"), ref("power")]

interface2 = [ref("errorcode"), ]

interface3 = [ref("temperature"), ref("power"), ref("errorcode")]
# set temperature to 300K
ref("temperature") = 300.0

# interfaces
print (interface1[ref("temperature")]) --> 300K
print (interface3[ref("temperature")]) --> 300K

如何在 Python 中执行此操作以及如何执行此 pythonic?

您可以将 "instance-container" 放在 class 本身中:

class DataPoint:
    instances = {}

    def __init__(self, name, typeUUID, value=None):
        self.name = name
        self.typeUUID = typeUUID
        self.value = value

        self.instances[name] = self

    @classmethod
    def get(cls, name):
        return cls.instances[name]

那么你可以这样使用它:

>>> d1 = DataPoint("foo", "12345")
>>> d2 = DataPoint("bar", "67890")

>>> DataPoint.get("foo")
<DataPoint object at 0x.........>