Why do you not have to return objects in Python?

  • A+
Category:Languages

I am a newbie to Python and programming in general and I have just gotten into OOP. In Python, whatever is defined in a function's namespace is only valid while inside that namespace; once outside that space things like variables are forgotten:

def foo():     a = 3  print(a)  NameError: name 'a' is not defined 

As far as I know, besides returning data from functions, any information inside the function is lost at the end of the function call, and therein lies my question. Take the following code:

class Example:      def __init__(self, name):         self.name = name      def foo(self):         self.name = 'John'  bar = Example('Jake') bar.foo() print(bar.name)  'John' 

My question is: why don't you have to return objects after methods? In normal functions any variables are forgotten, but in methods it seems data is actually appended to the object itself, such as the foo() method being able to reference self.name despite self.name first being referenced in another method. Is this correct? Or is there a better technical explanation?

 


First, you don't have to return a value in a method, not in python, and not in many other programming languages. for example:

def append_a(lst):     lst.append('a')  bob = [] append_a(bob) print(bob) ['a'] 

Above we do not return anything in the function, but we use it to modify an existing data structure, this is very common almost anywhere.

Secondly, in your second example, you created an instance of the class Example, when you look at self.something you are looking at a member of the class, unlike other languages, where often members are only declared once, in python you can dynamically add members.
Thus when looking at bar.name you are looking at a member of the class, its value on the instance bar. If you would look at a different instance, the value will be different.

class Example:      def __init__(self, name):         self.name = name      def foo(self):         self.name = 'John'  bar = Example('Jake') bob = Example('Bob') bar.foo() print(bar.name) print(bob.name)  John Bob 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: