简体   繁体   中英

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 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)

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

so I can simply call l1.length()>l2.length() in findLine .

Also, the data metric might be stored in a large data frame. 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.

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 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. Any instance will have the same value for metric . You can access the value for metric within the instance by calling the original Line class as opposed to self .

If you want metric to occur only in some instances but not others, you had better add it as an instance attribute:

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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