Inheritance problem...

Why is my custom class not functioning?

Page 1 of 1

2 Replies - 740 Views - Last Post: 22 June 2009 - 07:29 PM Rate Topic: -----

#1 code_m  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 24
  • View blog
  • Posts: 202
  • Joined: 21-April 09

Inheritance problem...

Posted 21 June 2009 - 02:58 PM

( Python, 3.0 )

I have defined a class called Money_value in which I want to inherit the float class, but whenever I do something that is not defined by the new class, the variable becomes float ?

class Money_value(float):
    def __str__(self):
        """Return a "beautified" string, to look more like a standard 2-decimal money value
        """
        value_list = super().__str__().split(".")
        if len(value_list[1]) == 1:
            return "$" + value_list[0] + "." + value_list[1] + "0"
        else:
            cent_list = [x for x in value_list[1]]

            # round the second decimal if needed
            if len(cent_list) > 2 and int(cent_list[2]) >= 5:
                cent_list[1] = str(int(cent_list[1]) + 1)

            return "$" + value_list[0] + "." + "".join(cent_list[:2])



so lets say I want to do this:
>>> value = Money_value(83.45)
>>> value += 2.30
>>> type(value)
<class 'Money_value'>



I get this:
>>> value = Money_value(83.45)
>>> value += 2.30
>>> type(value)
<class 'float'>



I can even do:
>>> value = Money_value(83.45)
>>> value += Money_value(2.30)
>>> type(value)
<class 'float'>



I'm so confused as to why any variable continues to silently becomes float?

Is This A Good Question/Topic? 0
  • +

Replies To: Inheritance problem...

#2 crazyjugglerdrummer  Icon User is offline

  • GAME OVER. NERD WINS.
  • member icon

Reputation: 119
  • View blog
  • Posts: 690
  • Joined: 07-January 09

Re: Inheritance problem...

Posted 21 June 2009 - 03:03 PM

interesting, possibly they're gettting downcast to float since the += is an operator taking a float, unless you extended and implemented it yourself. I haven't heard much about people extending number classes, as normally you want a hasa relationship instead of isa, but do whatever you like . ;D
Was This Post Helpful? 0
  • +
  • -

#3 code_m  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 24
  • View blog
  • Posts: 202
  • Joined: 21-April 09

Re: Inheritance problem...

Posted 22 June 2009 - 07:29 PM

I suppose it would be easier to just use a simple function for the str conversion, but I was going for a fully object-oriented approach, and making such a change without inheritance would be outside of this realm.

Oh well.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1