如何在Python中将一个类的实例保存为其自身类变量?

2024-04-19 10:30:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图定义一个类,它本身有一个实例作为类变量,这样我就可以到处引用它的一个公共实例。你知道吗

我怎么能让这样的东西工作呢?你知道吗

class Point():
  ORIGIN = Point()

  def __init__(self, x=0, y=0):
    self.x = x
    self.y = y

p0 = Point.ORIGIN
p1 = Point(3,4)

distance = (p1.x*p1.x + p1.y*p1.y) ** .5
print(distance)

Tags: 实例self定义initdeforiginclassdistance
3条回答

只需创建表示所需值的类变量,而不是将这些值封装在实例中:

class Point:
    x = 0
    y = 0
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

x,y = Point.x, Point.y
p1 = Point(3,4)
distance = ((p1.x-x)**2 + (p1.y-y)**2) ** .5
print(distance) # prints 5.0

或者,更好的是:

class Point:
    x = 0
    y = 0
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def distance(self, other=None):
        if other is None:
            x,y = Point.x, Point.y
        else:
            x,y = other.x, other.y
        return ((self.x-x)**2 + (self.y-y)**2) ** .5

然后你可以这样做:

>>> p1 = Point(3,4)
>>> p1.distance()
5.0
>>> p1.distance(Point(3,5))
1.0

你可以使用一个元类:

>>> class SingletonMeta(type):
...     def __init__(cls, name, bases, dct):
...         cls.ORIGIN = cls()
...
>>> class Point(metaclass=SingletonMeta):
...     def __init__(self, x=0, y=0):
...         self.x = x
...         self.y = y
...
>>> p0 = Point.ORIGIN
>>> p1 = Point(3,4)
>>> p0
<__main__.Point object at 0x110b7e7b8>
>>> p0.x, p0.y
(0, 0)

可以在创建类之后添加类属性

class Point():
  def __init__(self, x=0, y=0):
    self.x = x
    self.y = y

Point.ORIGIN = Point()

您可能还可以让它工作,以便通过描述符懒洋洋地创建源代码,或者您可能可以使用元类做一些奇怪的事情,但这似乎不值得您花时间。你知道吗

相关问题 更多 >