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?
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?
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
.
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
No, it will not "assign to the object". Basically, your code will do two things:
Create a variable self
that is local to foo.__init__
:
>>> class foo:
... def __init__(self):
... self = 'hi'
... print(self)
...
>>> foo()
'hi'
>>>
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'
>>>