[英]How can I save an instance of a class in it's own class as a class variable in 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)
您可以在創建類后添加class屬性:
class Point():
def __init__(self, x=0, y=0):
self.x = x
self.y = y
Point.ORIGIN = Point()
你也可以讓它工作,以便通過描述符懶惰地創建原點,或者你可以使用元類做一些時髦的東西 - 但這似乎不值得你花時間。
您可以使用元類:
>>> 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:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.