Skip to content Skip to sidebar Skip to footer

Resolving How To Give An Attribute In A Class In Python

I have the following class: class Point(object): __slots__= ('x','y','z','data','classification') def __init__(self,x,y,z,n=None): self.x = float(x) self.y

Solution 1:

You could use a property to handle classification instead:

classPoint(object):
    __slots__= ("x", "y", "z", "data", "_classification")
    def__init__(self, x, y, z):
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)
        self.data = [self.x,self.y,self.z]

    @propertydefclassification(self):
        returngetattr(self, '_classification', None)

    @classification.setterdefclassification(self, value):
        self._classification = value
        if value:
            self.data = self.data[:3] + [value]
        else:
            self.data = self.data[:3]

This sets up a getter and a setter for a classification attribute; accessing the classification attribute translates into the first method being called. Setting the classification attribute translates in the setter, the second method, being called instead:

p = Point(1, 2, 3)
p.classification = 50  # calls the second `classification` method, the setter, for you.print p.classification # calls the first `classification` method, the getter.

I picked the classification attribute as the property here, but you could make data a property instead as well. Which one you make into a property depends on usage patterns and intent. If classification is rarely changed, making it the property would be more efficient.

Solution 2:

Getter and setter methods are generally frowned upon. You can use a property to achieve this, however I'd recommened to always include classification in your return value, just because other parts of your script might expect that data is always a 4-item list. APIs should be consistent.

Here's my take on it using a property:

classPoint(object):
    __slots__= ("x", "y", "z", "data", "classification")
    def__init__(self, x, y, z, n=None):  ## what's n for?
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)

        self.classification = None    @propertydefdata(self):
        if self.classification:
            return [self.x, self.y, self.z, self.classification]
        else:
            return [self.x, self.y, self.z]

p = Point(10, 20, 30)
print p.data   ## [10.0, 20.0, 30.0]
p.classification = 50.0print p.data   ## [10.0, 20.0, 30.0, 50.0]

Post a Comment for "Resolving How To Give An Attribute In A Class In Python"