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
只需创建表示所需值的类变量,而不是将这些值封装在实例中:
或者,更好的是:
然后你可以这样做:
你可以使用一个元类:
可以在创建类之后添加类属性:
您可能还可以让它工作,以便通过描述符懒洋洋地创建源代码,或者您可能可以使用元类做一些奇怪的事情,但这似乎不值得您花时间。你知道吗
相关问题 更多 >
编程相关推荐