drako234
drako234

Reputation: 129

How do I convert a class property to integer

I have the following class:

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

I need to use it to compare against a number following this logic:

if num <= temp_con.t - 2:
    #dothing

However i get the error:

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

I have tried int(temp_con.t) and getattr(temp_con, t) but those did not work.

How can I utilize the property as an int?

Upvotes: 2

Views: 6810

Answers (3)

JohanL
JohanL

Reputation: 6891

You need an instance of the class in order to use the property and, as pointed out in other answers, you need to use a different name for your object variable. Try:

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

Thus, to access the value of the property and not the property function, you have to access it through my_temp_con.t.

Upvotes: 0

Radosław Cybulski
Radosław Cybulski

Reputation: 2992

You're accessing t on CLASS, not on an OBJECT of CLASS.

Try:

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

In you code temp_con.t returns property object, which wraps getter (and setter) you've defined in your class code, but it doesnt execute it.

UPDATE: (memo: read twice) There's also another problem with your code. First (well, it's second in code, but it will happen first) you define getter t, then later you OVERWRITE it with self.t = 0. As a result you'll get (as t) property accessible as a class member (which happens in your example) and value 0 as object's member.

Upvotes: 1

chepner
chepner

Reputation: 531055

You need to use separate names for the property and the attribute it wraps. A good convention is to use the property name prefixed with a _ as the attribute name.

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

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

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

Then you can access the property on an instance of the class.

temp_con = TempCon()
print(temp_con.t)
temp_con.t = 5
print(temp_con.t)

Upvotes: 6

Related Questions