[英]Using a fixed attribute for multiple objects
對不起,標題令人困惑,因為我真的不知道如何描述這個問題。 我將嘗試用一個例子來解釋。
假設我要寫一個 class
class Line:
def __init__(self, x1, y1, x2, x3):
self.start = (x1, y1)
self.end = (x2, y2)
def length(self, metric):
# return the length of this line using the input metric
這里metric
是平面上的一個metric(可能是一個function,也可能是一個table等,這里不重要)
現在我想做類似的事情
def findLine(metric):
l1 = Line(0,0,1,1)
l2 = Line(0,0,2,2)
# just an example, I may need to create a lot of lines then compare their length
if l1.length(metric)>l2.length(metric):
return l1
我正在尋找一種方法,以某種方式為metric
中findLine
的所有行設置默認值
所以我可以簡單地在findLine
中調用l1.length()>l2.length()
。
此外,數據metric
可能存儲在大型數據框中。 我認為將它們存儲在每一行中可能不太好。
抱歉造成混淆。 我只是想找到一種方法來簡化我的代碼。
我應該在我的代碼中添加,有 5 或 6 個這樣的參數,而不僅僅是一個。
這就是我想找到一種方法,而不是每次都寫所有參數的原因。
謝謝!
您可以使用 class 屬性:
class Line:
metric = (1,2)
def __init__(self, x1, y1, x2, y2):
self.start = (x1, y1)
self.end = (x2, y2)
def length(self):
return Line.metric+self.start
# return the length of this line using the input metric
l = Line(1,2,3,4)
m = Line(4,5,6,7)
print(l.metric)
print(m.metric)
print(l.length())
print(m.length())
這屬於 class 而不是實例。 任何實例都將具有相同的metric
值。 您可以通過調用原始Line
class 而不是self
來訪問實例中的metric
值。
如果您希望metric
僅在某些實例中出現而不在其他實例中出現,您最好將其添加為實例屬性:
class Line:
def __init__(self, x1, y1, x2, y2, metric=None):
self.start = (x1, y1)
self.end = (x2, y2)
self.metric = metric
def length(self):
if self.metric is not None:
return self.metric + self.start
else:
return 'Line has no metric'
# return the length of this line using the input metric
metric1 = (1,2)
metric2 = (2,3)
l = Line(1, 2, 3, 4, metric=metric1)
m = Line(4, 5, 6, 7, metric=metric2)
n = Line(8, 9, 10, 11)
print(l.metric)
print(m.metric)
print(l.length())
print(m.length())
print(n.length())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.