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..?
#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


Messages In This Thread
The self variable in a class..? - by mitmit293 - Feb-07-2019, 08:54 PM
RE: The self variable in a class..? - by micseydel - Feb-07-2019, 10:03 PM
RE: The self variable in a class..? - by mitmit293 - Feb-07-2019, 10:47 PM
RE: The self variable in a class..? - by stullis - Feb-08-2019, 02:42 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable Types in a class nafshar 9 2,473 Oct-07-2022, 07:13 PM
Last Post: deanhystad
  can Inner Class reference the Outer Class's static variable? raykuan 6 5,929 Jul-01-2022, 06:34 AM
Last Post: SharonDutton
  Calling a base class variable from an inherited class CompleteNewb 3 1,695 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,996 Nov-13-2020, 03:43 AM
Last Post: SalsaBeanDip
  Class variable / instance variable ifigazsi 9 4,316 Jul-28-2020, 11:40 AM
Last Post: buran
  Assignment of non-existing class variable is accepted - Why? DrZ 6 4,279 Jul-13-2020, 03:53 PM
Last Post: deanhystad
  Limiting valid values for a variable in a class WJSwan 5 3,634 Jul-06-2020, 07:17 AM
Last Post: Gribouillis
  Newbie: Help with variable selection in a class Slack86 5 2,736 Apr-07-2020, 08:41 PM
Last Post: jefsummers
  Using variable from a class in another .py script keegan_010 4 2,995 Mar-25-2020, 07:47 AM
Last Post: keegan_010
  How to access class variable? instances vs class drSlump 5 3,352 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