[英]Using a fixed attribute for multiple objects
Sorry for the confusing title because I really don't know how to describe this question.对不起,标题令人困惑,因为我真的不知道如何描述这个问题。 I will try to use an example to explain.我将尝试用一个例子来解释。
Say I want to write a class假设我要写一个 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
Here metric
is a metric on the plane (it might be a function, or a table etc, not important here)这里metric
是平面上的一个metric(可能是一个function,也可能是一个table等,这里不重要)
Now I want to do something like现在我想做类似的事情
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
I am looking for a way that somehow setting a default value for metric
for all the lines used in findLine
我正在寻找一种方法,以某种方式为metric
中findLine
的所有行设置默认值
so I can simply call l1.length()>l2.length()
in findLine
.所以我可以简单地在findLine
中调用l1.length()>l2.length()
。
Also, the data metric
might be stored in a large data frame.此外,数据metric
可能存储在大型数据框中。 I think it might be not good to store them in each line.我认为将它们存储在每一行中可能不太好。
Sorry for the confusing.抱歉造成混淆。 I am just trying to find a way to simplify my code.我只是想找到一种方法来简化我的代码。
I should add that in my code, there are 5 or 6 these kind of parameters not just one.我应该在我的代码中添加,有 5 或 6 个这样的参数,而不仅仅是一个。
That's the reason I want to find a way to not writing all parameters every time.这就是我想找到一种方法,而不是每次都写所有参数的原因。
Thanks!谢谢!
You could use a class attribute:您可以使用 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())
This belongs to the class and not the instance.这属于 class 而不是实例。 Any instance will have the same value for metric
.任何实例都将具有相同的metric
值。 You can access the value for metric
within the instance by calling the original Line
class as opposed to self
.您可以通过调用原始Line
class 而不是self
来访问实例中的metric
值。
If you want metric
to occur only in some instances but not others, you had better add it as an instance attribute:如果您希望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.