1

I am working on a class in python and I don't know if I can assign to an object inside one of its methods. For example:

class foo:
    def __init__(self):
        self = <something>

Is that assignment (line 3) is right?

glglgl
  • 89,107
  • 13
  • 149
  • 217
TulkinRB
  • 590
  • 1
  • 6
  • 10
  • 1
    The answer is "yes you can". But, why would you do that? – Paulo Bu Jan 11 '14 at 19:48
  • 2
    What would you expect that assignment to do? – murgatroid99 Jan 11 '14 at 19:48
  • You can assign to the name `self`, but that does not "assign to the object". It won't have any effect on the object. – BrenBarn Jan 11 '14 at 19:50
  • The only reasonable place to modify self (as opposed to initialize some self's args) is a constructor, in Python this is not `__init__` but `__new__` method. Probably, this answer http://stackoverflow.com/a/674369/1265154 is worth reading. – alko Jan 11 '14 at 19:53

3 Answers3

2

You can assign to the name self, but that does not "assign to the object". It won't have any effect on the object. It just assigns a value to a local variable called self.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
2

self is a reference to an object. If you assign to it, you change which object the variable self is referring to, but it does not modify anything outside that method.

The functionality is similar to the following code:

def change(a):
    a = 10
    print(a) # prints 10

x = 5
change(x)
print(x) # prints 5
kazagistar
  • 1,537
  • 8
  • 20
2

No, it will not "assign to the object". Basically, your code will do two things:

  1. Create a variable self that is local to foo.__init__:

    >>> class foo:
    ...     def __init__(self):
    ...         self = 'hi'
    ...         print(self)
    ...
    >>> foo()
    'hi'
    >>>
    
  2. Afterwards, the self argument that was given to foo.__init__ upon initialization of class foo will be overwritten. In other words, after that line, you can no longer create instance attributes for foo:

    >>> class foo:
    ...     def __init__(self):
    ...         self = 'hi'
    ...         print(self)
    ...         self.attr = 'hello'
    ...
    >>> foo()
    hi
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 5, in __init__
    AttributeError: 'str' object has no attribute 'attr'
    >>>
    

In summary, you can do what you described, but you really shouldn't. It doesn't do anything positive for your code. Instead, it will most likely cause problems later on. And even if it doesn't, it will still confuse people reading your code.


Perhaps by "assign to the object", you meant that you want to make an instance attribute for foo? If so, then the syntax would be like this:

class foo:
    def __init__(self):
        self.<attribute name> = <something>

Below is a demonstration:

>>> class foo:
...     def __init__(self):
...         self.my_attribute = 'value'
...
>>> test = foo()
>>> test.my_attribute
'value'
>>>