如何解决对多个对象使用固定属性
抱歉,标题令人困惑,因为我真的不知道如何描述这个问题。 我将尝试用一个例子来解释。
说我想写一个课
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
是平面上的一个指标(它可能是函数或表等,此处不重要)
现在我想做类似的事情
def findLine(metric):
l1 = Line(0,1,1)
l2 = Line(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
的默认值的方式
所以我可以简单地在l1.length()>l2.length()
中呼叫findLine
。
此外,数据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())
这属于类而不是实例。任何实例的metric
都将具有相同的值。您可以通过调用原始metric
类而不是Line
来访问实例中self
的值。
如果您希望metric
仅在某些实例中出现,而在其他实例中不出现,则最好将其添加为实例属性:
class Line:
def __init__(self,y2,metric=None):
self.start = (x1,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,4,metric=metric1)
m = Line(4,7,metric=metric2)
n = Line(8,9,10,11)
print(l.metric)
print(m.metric)
print(l.length())
print(m.length())
print(n.length())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。