繁体   English   中英

对多个对象使用固定属性

[英]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

我正在寻找一种方法,以某种方式为metricfindLine的所有行设置默认值

所以我可以简单地在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM