Python Forum
How are these methods working within this class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How are these methods working within this class
#1
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()
Reply
#2
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.
Reply
#3
Thank you...
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Class test : good way to split methods into several files paul18fr 4 471 Jan-30-2024, 11:46 AM
Last Post: Pedroski55
  Structuring a large class: privite vs public methods 6hearts 3 1,049 May-05-2023, 10:06 AM
Last Post: Gribouillis
  access share attributed among several class methods drSlump 0 1,058 Nov-18-2021, 03:02 PM
Last Post: drSlump
  a function common to methods of a class Skaperen 7 2,577 Oct-04-2021, 07:07 PM
Last Post: Skaperen
  Listing All Methods Of Associated With A Class JoeDainton123 3 2,339 May-10-2021, 01:46 AM
Last Post: deanhystad
  too many methods in class - redesign idea? Phaze90 3 2,488 Mar-05-2021, 09:01 PM
Last Post: deanhystad
  Special Methods in Class Nikhil 3 2,269 Mar-04-2021, 06:25 PM
Last Post: Nikhil
  cant able to make methods interact with each other in the class jagasrik 2 1,794 Sep-16-2020, 06:52 PM
Last Post: deanhystad
  Question about naming variables in class methods sShadowSerpent 1 2,002 Mar-25-2020, 04:51 PM
Last Post: ndc85430
  a class calling one of its own methods? Skaperen 1 1,833 Jul-21-2019, 04:43 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020