Python Forum
How are these methods working within this class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How are these methods working within this class (/thread-6567.html)



How are these methods working within this class - workerbee - Nov-29-2017

I was wondering how the self.data attribute gets into the display method from the setdata method .Thank You
class FirstClass:

	def setdata(self, value):
		self.data = value 
	def display(self):
		print(self.data)
		
		
obj = FirstClass()

obj.setdata(10)
obj.display()



RE: How are these methods working within this class - Mekire - Nov-29-2017

When you write:
obj.setdata(10)
obj is implicitly passed as the first argument to the method.

For example, this is identical:
FirstClass.setdata(obj, 10)
 Same for display:
obj.display() is actually FirstClass.setdata(obj).
Since the data attribute of obj has been set, and display has access to obj you can access obj.data inside the display function.

This is an instance attribute. Class instances encapsulate their own data so you don't need to pass all the state arguments around.


RE: How are these methods working within this class - workerbee - Nov-29-2017

Thank you...


RE: How are these methods working within this class - hshivaraj - Nov-29-2017

Quote: I was wondering how the self.data attribute gets into the display method from the setdata method .Thank You
As an experiment, try removing the "self" keyword from the self.data from set setData method. And see what happen?

You will notice an Exception, this is because, when you prefix a variable with the "self" keyword, it immediately becomes a persistent object, meaning, the scope of that variable is constrained to the function setData scope, but for the entire class. Hence you were able to access the self.data from display function.