如何将类属性转换为integ

2024-05-14 16:54:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下课程:

class temp_con():
    def __init__(self):
        self.t = 0
    @property
    def t(self):
        return self.t
    @t.setter
    def t(self,value):
        self.t = value

我需要用它来比较一个遵循这个逻辑的数字:

^{pr2}$

但是我得到了一个错误:

Type error: unsupported operand type for -: 'property' and 'int'<

我试过int(temp_con.t)和{},但都没用。在

如何将属性用作int?在


Tags: selfreturninitvaluedef数字property逻辑
3条回答

您需要为属性及其包装的属性使用单独的名称。一个好的约定是使用前缀为_的属性名作为属性名。在

class TempCon:
    def __init__(self):
        self._t = 0

    @property
    def t(self):
        return self._t

    @t.setter
    def t(self, value):
        self._t = value

然后可以访问类的实例上的属性。在

^{pr2}$

为了使用属性,您需要一个类的实例,并且,正如其他答案中所指出的,您需要为您的对象变量使用不同的名称。尝试:

class temp_con():
    def __init__(self):
    self._t = 0
@property
    def t(self):
    return self._t
@t.setter
    def t(self,value):
    self._t = value

my_temp_con = temp_con()

if num <= my_temp_con.t - 2:
    pass

因此,要访问属性的值而不是属性函数,必须通过my_temp_con.t来访问它。在

你在类上访问t,而不是类的对象。在

尝试:

q = temp_con()
if num <= q.t - 2:
  pass

在您的代码temp_con.t返回property对象,它包装了您在类代码中定义的getter(和setter),但它不执行它。在

更新:(备注:读两遍) 你的代码还有另一个问题。首先(好吧,这在代码中是第二个,但它会首先发生)您定义getter t,然后用self.t = 0覆盖它。结果,您将获得(作为t)属性作为类成员访问(在您的示例中发生),值0作为对象的成员。在

相关问题 更多 >

    热门问题