Bottom Page

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
Quote
#2
I'd say no. Could you elaborate? Depending on what you mean, the answer could be an elaborate yes / sort of.
Quote
#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
Quote
#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?
snippsat likes this post
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  How to store the value from variable into list & run a statement then put in variable searching1 1 294 May-29-2019, 06:36 AM
Last Post: heiner55
  Call a varaible from class in the parent class Clement_2000 1 314 May-09-2019, 11:14 PM
Last Post: michalmonday
  Naming a variable with the str value and another variable SheeppOSU 2 277 Apr-21-2019, 07:18 PM
Last Post: ichabod801
  Get variable from another class Golfball2k6 1 188 Apr-06-2019, 01:40 PM
Last Post: ichabod801
  Get variable from class inside another class hcne 3 265 Mar-30-2019, 03:02 PM
Last Post: ichabod801
  Trying to set an instance variable to current value of a class variable ScottDiesing 3 281 Feb-15-2019, 03:12 PM
Last Post: ScottDiesing
  Why Can't I call base class function for my derived class object? AmirAB 2 287 Feb-13-2019, 03:04 PM
Last Post: snippsat
  Calling a class inside other class dan789 9 517 Jan-06-2019, 02:00 PM
Last Post: dan789
  Class object instance. Link instance attribute to class. Can it be done easier. Windspar 7 534 Dec-03-2018, 11:16 PM
Last Post: Windspar
  Is it possible to create a variable with the name of an output of another variable Panda 8 948 Jun-06-2018, 09:14 PM
Last Post: Panda

Forum Jump:


Users browsing this thread: 1 Guest(s)