解决如何给一个属性在Python中的类 [英] Resolving how to give an attribute in a class in Python

查看:89
本文介绍了解决如何给一个属性在Python中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

class Point(object):
    __slots__= ("x","y","z","data","classification")
    def __init__(self,x,y,z,n=None):
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)
        self.data = [self.x,self.y,self.z]

    def set_classification(self,n):
        self.classification = n

p = Point(10,20,30)
p.data
[10.0, 20.0, 30.0]
p.set_classification(0)
p.data
[10.0, 20.0, 30.0]

我有以下问题:

首先,参数创建Point对象是 X,Y 以Z 分类是一个配件的参数(有些时间是其他文件中报告中没有)。我想找到一种方法,如果有可能,有
p.data = 10.0,20.0,30.0,50.0] 时,分类设置或 p.data = 10.0,20.0,30.0] 时没有设置分类。

First, the parameters to create the Point object are x,y, and z. Classification is an accessory parameter (some time is report inside the file other no). I wish to find a way, if it's possible, to have p.data = [10.0, 20.0, 30.0, 50.0] when classification is set or p.data = [10.0, 20.0, 30.0] when classification is not set.

第二,我用 set_classification

def set_classification(self,n):
      self.classification = n

这是正确的蟒蛇API的风格?我看了几个论坛帖子,但我仍然感到困惑。

Is this the correct python API style? I read several forum posts, but I am still confused.

推荐答案

您可以使用的 属性 来处理,而不是分类:

You could use a property to handle classification instead:

class Point(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]

    @property
    def classification(self):
        return getattr(self, '_classification', None)

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

此设置了一个getter和一个分类属性的制定者;访问分类属性转换成第一个方法被调用。设置分类属性在二传手翻译,第二种方法,被称为代替:

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.

这篇关于解决如何给一个属性在Python中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆