Python Forum
The self variable in a class..?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The self variable in a class..?
#1
Is it like the 'i' variable in
 for i in Range
Reply
#2
I'd say no. Could you elaborate? Depending on what you mean, the answer could be an elaborate yes / sort of.
Reply
#3
Just trying to figure out what that'self' is doing in a class.
When ever I ask a question on the forum, I get a very professionelle techish answer. Problem is, as a newbie I dont understand an answer like that. Explain it, as if you were talking to an idiot please
Reply
#4
Self, as you can imagine, is a self-referential parameter. In essence, it's telling the method where data are stored. Let's say we have a class called Dog:

class Dog:

    def __init__(self, sound):
        self.sound = sound

    def bark(self):
        return self.sound
When we call the Dog.bark() method, the method needs to know where the data are. Where is this particular dog (named Bacon because I have bacon on the brain right now)? Where can I find Bacon.sound? To satisfy that need, the class passes itself to its methods. Another way to think of if it to imagine a function that takes a Dog as an argument:

def bark(pet):
    return pet.sound

Bacon = Dog("woof")

assert Bacon.sound == bark(Bacon)
The Dog.bark() (or Bacon.sound (which is "sizzle", truly)) does the same as the bark() function. It just passes itself into the method. This way, methods can use the same underlying infrastructure as regular functions.

Did that help?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable Types in a class nafshar 9 2,364 Oct-07-2022, 07:13 PM
Last Post: deanhystad
  can Inner Class reference the Outer Class's static variable? raykuan 6 5,775 Jul-01-2022, 06:34 AM
Last Post: SharonDutton
  Calling a base class variable from an inherited class CompleteNewb 3 1,595 Jan-20-2022, 04:50 AM
Last Post: CompleteNewb
  Can we access instance variable of parent class in child class using inheritance akdube 3 13,889 Nov-13-2020, 03:43 AM
Last Post: SalsaBeanDip
  Class variable / instance variable ifigazsi 9 4,222 Jul-28-2020, 11:40 AM
Last Post: buran
  Assignment of non-existing class variable is accepted - Why? DrZ 6 4,189 Jul-13-2020, 03:53 PM
Last Post: deanhystad
  Limiting valid values for a variable in a class WJSwan 5 3,514 Jul-06-2020, 07:17 AM
Last Post: Gribouillis
  Newbie: Help with variable selection in a class Slack86 5 2,694 Apr-07-2020, 08:41 PM
Last Post: jefsummers
  Using variable from a class in another .py script keegan_010 4 2,912 Mar-25-2020, 07:47 AM
Last Post: keegan_010
  How to access class variable? instances vs class drSlump 5 3,286 Dec-11-2019, 06:26 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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