Page 1 of 4 123 ... LastLast
Results 1 to 10 of 32

Thread: In Python, what does "x = 5" really do/mean?

  1. #1
    Join Date
    Apr 2007
    Beans
    226
    Distro
    Ubuntu 10.04 Lucid Lynx

    In Python, what does "x = 5" really do/mean?

    Hi,

    I'm a great scripter, but just learning programming (using Python).

    I'm very much a newbie at this, so please be patient as I'm sure these will seem so basic a questions and may seem stupid to those experienced.

    I'm reading a python book right now that has me thinking about variables.

    As the title says, what does "x=5" really mean?

    What is the "5" being assigned to? Is "x" considered an "instance" of "int?"

    If I do this:
    Code:
    >>> class test(int):
        pass
    
    >>> x=test(5)
    >>> x
    5
    >>>
    Then x here is an instance of class test(), a subclass of int.

    But with int, you can do x=5.

    If I do that after the above code, then x is no longer an instance of test() but is a variable of type int().

    In the above, what is the 5 actually being assigned to in the instance of test()?

    I have accessed it by defining a class and doing this just messing around:

    Code:
    >>> class test2(int):
        def value(self):
            print self
            self += 1
            print self
    
            
    >>> x=test2(5)
    >>> x
    5
    >>> x.value()
    5
    6
    >>> x
    5
    Why doesn't the value of x change to 6 in the above example? I'm I "redefining" self in the value() method to no longer reflect what is self in the instance?

    Also, can I "hijack" what x=5 means to to add my own methods, but it still behave like x=5. What I mean might be explained by this code:

    Code:
    #do whatever code here to "hijack" int()
    
    >>> x=5
    >>> x
    5
    >>> x.make_negative
    >>> x
    -5
    >>> x=-2
    >>> x
    -2
    >>> x.make_negative
    >>> x
    2
    Or something like that?

    If there is no way to do that and we go back to my original subclass definition, how do I change the value of the instance of the class to another value?

    In:
    Code:
    >>> x=5
    >>> x += 1
    >>> x
    6
    How does the value of x become incremented internally? What magic is happening behind the scenes?

    Say I want to do what is verboten in Python. Make in C-like incrementor like this.

    Code:
    >>> class Incrementor(int):
        def incAfter (self): # equivalent of x++
            #do whatever to access the value of instance
            return VALUE_OF_INSTANCE # as in x=Incrementor(5)
            VALUE_OF_INSTANCE += 1 # not quite sure how to do this to make it increment after returning the value (perhaps it is imporssible). Help here would be appreciated, too.
        def incBefore(self): # equivalent of ++x
            VALUE_OF_INSTANCE += 1
            return VALUE_OF_INSTANCE # as in x=Incrementor(5)
    So that I could do something like this:

    Code:
    >>> x = Incrementor(5)
    >>> x
    5
    >>> print x.incAfter()
    5
    >>> x
    6
    >>> print x.incBefore()
    7
    >>> x
    7
    Helping me with the concepts would really go a long way for me. Any help would be greatly appreciated.

    Thankfully,
    Narnie

  2. #2
    Join Date
    Nov 2005
    Location
    Bordeaux, France
    Beans
    11,294
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: In Python, what does "x = 5" really do/mean?

    Your mistake is here:

    How does the value of x become incremented internally? What magic is happening behind the scenes?
    It does not. A new object vith value 6 is created, and name x is bound to that object. int is an immutable type, meaning that once an object has been created, its value may not change. Otherwise you could as well do 0 = 1.

    As for your Incrementor class, you absolutely do not need to (and really, can't) make it inherit from int. Just create a base class with an int attribute:

    Code:
    class Incrementor(object):
        def __init__(self, value=0):
            self.__value = value
    
        def incAfter(self):
            # Can't do anything after the function returns!
            oldvalue = self.__value
            self.__value += 1
            return oldvalue
    
        def incBefore(self):
            self.__value += 1
            return self.__value
    Last edited by Bachstelze; June 22nd, 2010 at 10:13 PM.
    「明後日の夕方には帰ってるからね。」


  3. #3
    Join Date
    Aug 2007
    Location
    UK
    Beans
    427
    Distro
    Ubuntu UNR

    Re: In Python, what does "x = 5" really do/mean?

    Quote Originally Posted by narnie View Post
    Hi,
    Code:
    >>> class test2(int):
        def value(self):
            print self
            self += 1
            print self
    
            
    >>> x=test2(5)
    >>> x
    5
    >>> x.value()
    5
    6
    >>> x
    5
    Why doesn't the value of x change to 6 in the above example? I'm I "redefining" self in the value() method to no longer reflect what is self in the instance?
    The instance is passed into the value method as the first argument and bound to local variable self.

    When you call self += 1 this calls the __add__ method of test2 which is inherited from int so you get the equivalent:
    Code:
    self = int.__add__(self, 1)
    Which assigns an int that is the sum of self and 1 to local variable self thus depriving the remaining code in the method of any opportunity to interact with the instance.

  4. #4
    Join Date
    Apr 2007
    Beans
    226
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: In Python, what does "x = 5" really do/mean?

    Quote Originally Posted by StephenF View Post
    The instance is passed into the value method as the first argument and bound to local variable self.

    When you call self += 1 this calls the __add__ method of test2 which is inherited from int so you get the equivalent:
    Code:
    self = int.__add__(self, 1)
    Which assigns an int that is the sum of self and 1 to local variable self thus depriving the remaining code in the method of any opportunity to interact with the instance.
    StephenF,

    Thank you for letting me know how the += operator works internally. This makes sense to and is helping my (early) understanding of what is going on.

    Gratefully,
    Narnie

  5. #5
    Join Date
    Apr 2007
    Beans
    226
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: In Python, what does "x = 5" really do/mean?

    OK, both of the answers above were very helpful, and I know I asked a lot in one post.

    I'm curious now what exactly "x" is in:

    Code:
    >>> x = 5
    >>> x
    5
    Why is "x" callable (if that is the right word) without adding () as in:

    Code:
    >>> x()
    5
    Can I duplicate this in my own class so I could do something like:

    Code:
    >>> # whatever code necessary to make a int variable bind to my function and use my additional methods
    >>> x=5
    >>> x
    5
    >>> x.incAfter() # now I can use my method on this new I have defined
    >>> x # and I can call my redefined variable without "()" at the end.
    6
    If not, how does x=5 work in the first place?

    Cheerio,
    Narnie

  6. #6
    -grubby is offline May the Ubuntu Be With You!
    Join Date
    Aug 2007
    Beans
    Hidden!

    Re: In Python, what does "x = 5" really do/mean?

    Quote Originally Posted by narnie View Post
    [...]
    Consider this:

    Code:
    >>> x = 5
    >>> x
    5
    >>> x.__repr__()
    '5'
    >>> repr(x)
    '5'
    >>> class Something:
    ...     def __repr__(self):
    ...             return "Cheese!"
    ... 
    >>> Something()
    Cheese!
    >>> repr(Something())
    'Cheese!'

  7. #7
    Join Date
    Aug 2007
    Location
    127.0.0.1
    Beans
    1,800
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: In Python, what does "x = 5" really do/mean?

    Quote Originally Posted by narnie View Post
    OK, both of the answers above were very helpful, and I know I asked a lot in one post.

    I'm curious now what exactly "x" is in:

    Code:
    >>> x = 5
    >>> x
    5
    Why is "x" callable (if that is the right word) without adding () as in:

    Code:
    >>> x()
    5
    Duck-typing my friend. Asking "x" in the interactive console, will ask for the __repr__ method (as the poster above me pointed out), and the terminal prints it pretty (without string quotation marks).

    On the other hand, callable objects have the __call__ method defined, so you could easily build an hybrid:

    PHP Code:
    >>> class weirdo(object):
    ...     
    def __repr__(self):
    ...             return 
    "Foo"
    ...     def __call__(self):
    ...             print 
    "Bar"
    ... 
    >>> 
    weirdo()
    >>> 
    x
    Foo
    >>> x()
    Bar 
    "Just in terms of allocation of time resources, religion is not very efficient. There's a lot more I could be doing on a Sunday morning."
    -Bill Gates

  8. #8
    Join Date
    Nov 2005
    Location
    Bordeaux, France
    Beans
    11,294
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: In Python, what does "x = 5" really do/mean?

    Quote Originally Posted by narnie View Post
    Can I duplicate this in my own class so I could do something like:

    Code:
    >>> # whatever code necessary to make a int variable bind to my function and use my additional methods
    >>> x=5
    >>> x
    5
    >>> x.incAfter() # now I can use my method on this new I have defined
    >>> x # and I can call my redefined variable without "()" at the end.
    6
    If not, how does x=5 work in the first place?
    You can't do that, because when you do x = 5, the previous "contents" of the variable x are completely forgotten, and some new content (in this case, a plain int with value 5) replaces it.

    What you can do is, instead of doing x = 5 to assign a new "value" to your object, do something like x.setValue(5):

    Code:
    class SuperInt(object):
        def __init__(self, value=0):
            self.__value = value
    
        def postInc(self):
            oldvalue = self.__value
            self.__value += 1
            return oldvalue
    
        def preInc(self):
            self.__value += 1
            return self.__value
    
        def setValue(self, value):
            self.__value = value
    
        def __repr__(self):
            return str(self.__value)
    Then

    Code:
    >>> from SuperInt import *
    >>> x = SuperInt(5)
    >>> x
    5
    >>> x.postInc()
    5
    >>> x
    6
    >>> x.preInc()
    7
    >>> x
    7
    >>> x.setValue(4)
    >>> x
    4
    Last edited by Bachstelze; June 23rd, 2010 at 02:27 AM.
    「明後日の夕方には帰ってるからね。」


  9. #9
    Join Date
    Apr 2007
    Beans
    226
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: In Python, what does "x = 5" really do/mean?

    Quote Originally Posted by -grubby View Post
    Consider this:

    Code:
    >>> x = 5
    >>> x
    5
    >>> x.__repr__()
    '5'
    >>> repr(x)
    '5'
    >>> class Something:
    ...     def __repr__(self):
    ...             return "Cheese!"
    ... 
    >>> Something()
    Cheese!
    >>> repr(Something())
    'Cheese!'
    Interesting. Thanks.

    Where is the value of x, which is 5, stored? It is some variable within the class?

    Narnie

  10. #10
    Join Date
    Apr 2007
    Beans
    226
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: In Python, what does "x = 5" really do/mean?

    Quote Originally Posted by Can+~ View Post
    Duck-typing my friend. Asking "x" in the interactive console, will ask for the __repr__ method (as the poster above me pointed out), and the terminal prints it pretty (without string quotation marks).

    On the other hand, callable objects have the __call__ method defined, so you could easily build an hybrid:

    PHP Code:
    >>> class weirdo(object):
    ...     
    def __repr__(self):
    ...             return 
    "Foo"
    ...     def __call__(self):
    ...             print 
    "Bar"
    ... 
    >>> 
    weirdo()
    >>> 
    x
    Foo
    >>> x()
    Bar 
    Ahh, IC. I tried using the __call__ method, but implemented it wrongly. I used "return" instead of "print." That is great for showing me the code. That makes sense.

    Is there a way to make it where I can set x (which is an instance of my class) with just an equals sign? Like x=5 where x will reflect my class, not the int type?

    Thanks again,
    Narnie

Page 1 of 4 123 ... LastLast

Bookmarks

Posting Permissions

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