thkang
thkang

Reputation: 11543

manipulating instance itself by its instance methods

I wonder if there is something similar to, say:

>>> class A(object):
...     def swap(self):
...         self = 'I am swapped'
... 
>>> abc=A()
>>> abc
<__main__.A object at 0x028B6130>
>>> abc.swap
<bound method A.swap of <__main__.A object at 0x028B6130>>
>>> abc.swap()
>>> abc
<__main__.A object at 0x028B6130>
>>> type(abc)
<class '__main__.A'>

see, it's type is not str, but Class A.

Upvotes: 2

Views: 139

Answers (3)

wim
wim

Reputation: 362766

You are confused - there is nothing special about assigning the name by using

self = 'I am swapped'

This is just binding the name self to a string object and it is acting as a local variable here. You are not mutating the parent object at all.

In fact, what you attempted is not used in Python because it's a strongly typed language. Instead, you would just make swap return a value, and then reassign the same variable name to the returned object in the outer scope.

Maybe this is easier to explain with code, instead of:

a.swap()

You would have:

a = a.swap()

Upvotes: 3

colons
colons

Reputation: 279

self is a convention. An instance of a class is what is handed to its functions in the first argument and you could call it whatever you like and you can do whatever you like to the local namespace in your particular function. See:

>>> class A:
...     def f(hats):
...         print hats
... 
>>> a = A()
>>> a.f()
<__main__.A instance at 0x100466908>

So yes, you can manipulate self in a class method, but since self itself doesn't actually mean anything, there's no real point. You should(n't) do what Joran suggested.

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113988

this is a terrible idea ... I do not advocate ever doing this ... In fact you should avoid at all costs ... look at using a Factory design pattern instead ...

>>> class A:
...    def swap(self):
...      self.__class__ = B
...
>>> class B:
...   pass
...
>>> a = A()
>>> a.swap()
>>> a
<__main__.B instance at 0x02C43E18>
>>>

Upvotes: 0

Related Questions