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.
Feel like you're not getting the answers you want? Checkout the help/rules for things like what to include/not include in a post, how to use code tags, how to ask smart questions, and more.

Pro-tip - there's an inverse correlation between the number of lines of code posted and my enthusiasm for helping with a question :)
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 access class variable? instances vs class drSlump 5 467 Dec-11-2019, 06:26 PM
Last Post: Gribouillis
  accessing local variable outside class priyanka08 3 214 Sep-24-2019, 10:00 AM
Last Post: buran
  Get variable from another class Golfball2k6 1 362 Apr-06-2019, 01:40 PM
Last Post: ichabod801
  Get variable from class inside another class hcne 3 515 Mar-30-2019, 03:02 PM
Last Post: ichabod801
  Trying to set an instance variable to current value of a class variable ScottDiesing 3 523 Feb-15-2019, 03:12 PM
Last Post: ScottDiesing
  Instantiating class from the string variable voltron 4 1,477 Feb-05-2018, 01:18 PM
Last Post: voltron
  What would be a way to check if a variable or class existed in an if? Klar 8 1,294 Dec-28-2017, 08:19 PM
Last Post: nilamo
  Can access class private variable? Michael 2 2,478 Aug-11-2017, 01:59 PM
Last Post: snippsat

Forum Jump:


Users browsing this thread: 1 Guest(s)