Reputation: 289
How can something be modified or added to a class?
For example, in the following code what does it mean that hello
can modify the a
I used in __init__
? I still have a lot of uncertainty on OOP, especially the relation between instantiation and other things.
I'm sure it's possible; if so, how can I do it?
class Foo:
def __init__(self, a):
self.a = a
def hello(self):
Upvotes: 3
Views: 145
Reputation: 52169
You are already successfully adding/modifying the class instance. Namely, __init__
takes some a
and adds it as the attribute .a
to the instance self
. Using the same name for the variable and attribute is incidental -- you could as well use different names:
class Bla:
def __init__(self, b):
self.a = b # add `b` as attribute `a`
Once an attribute is added to an instance, this attribute can by default be read and overridden freely. This applies to the initial method, other methods, and any other function/method having access to the instance.
class Bla:
def __init__(self, b):
self.a = b # add `b` as attribute `a`
def lol(self, c):
self.a = c # add `c` as attribute `a` (discarding previous values)
def rofl(self, d):
self.a += d # re-assign `self.a + d` as attribute `a`
# external function modifying `Bla` instance
def jk(bla, e):
bla.a = e # add `e` as attribute `a` (discarding previous values)
Upvotes: 1
Reputation: 2331
I'm not sure how Bla.lol() can modify the argument a
that is supplied to it, but it can alter the attribute Bla.a
or self.a
as it is referenced from within the object, which initially has the value of argument a
assigned to it.
We can have the function lol
assign a new value to the attribute a
, in this case I'm going to assume a
is a string, and extend the string with the phrase ' has been altered'
:
>>> class Bla:
... def __init__(self, a):
... self.a = a
...
... def lol(self):
... self.a += ' has been altered'
...
>>> instance = Bla('the arg a')
>>> instance.a # check a
'the arg a'
>>> instance.lol() # modifies a
>>> instance.a # check a again
'the arg a has been altered'
>>> instance.lol() # we can alter it again, as many times as we run the function
>>> instance.a # and see it has been altered a second time
'the arg a has been altered has been altered'
Upvotes: 1