Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    New Coder
    Join Date
    Feb 2006
    Posts
    60
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Python absolute newbie question

    Hi
    I wanted to verify that number literals are objects in Python as they are in Ruby, so I typed in dir(1) at the console.

    As I understand it, the + operator is actually calling __add__ behind the scenes.

    If that's right, is there any particular reason why 1.__add__(2) doesn't work?

    Apologies if this is a little basic!

  • #2
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by realtimethrill View Post
    Hi
    I wanted to verify that number literals are objects in Python as they are in Ruby, so I typed in dir(1) at the console.

    As I understand it, the + operator is actually calling __add__ behind the scenes.

    If that's right, is there any particular reason why 1.__add__(2) doesn't work?

    Apologies if this is a little basic!
    python is pure oop. the reason why 1.__add__(2) don't work is that the interpreter don't know what type is 1. try this:
    Code:
    one = 1
    one.__add__(2)
    best regards

  • #3
    New Coder
    Join Date
    Feb 2006
    Posts
    60
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thank you for the reply.

    What confuses me is that 1.2.__add__(2) does work.

  • #4
    New Coder
    Join Date
    Dec 2009
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts
    in 1.2, it thinks that 2 is a property of one (i think, im a python newb too)
    Open source. DO IT!!! SUPPORT IT!!! PREACH IT!!!
    -- The JSNerd

  • #5
    New Coder
    Join Date
    Dec 2009
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts
    what does it return? 4? 2? 3.2?
    Open source. DO IT!!! SUPPORT IT!!! PREACH IT!!!
    -- The JSNerd

  • #6
    Regular Coder Samhain13's Avatar
    Join Date
    Aug 2008
    Location
    Pilipinas
    Posts
    169
    Thanks
    4
    Thanked 18 Times in 18 Posts
    This works.
    Code:
    int(1).__add__(2)
    So maybe the interpreter needs to know that 1 is an integer. Same result with:
    Code:
    n = 1
    n.__add__(2)
    If 1.2.__add__(2) works, maybe that's because the presence of the "." automatically makes 1.2 a float, while simply "1" may be confused with a boolean? Dunno, but it seems to make sense.
    I am a Man of Truth. I am a Free Human Person. I am a Peacemaker.
    ** Independent Multimedia Artist in Pasig **


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •