-4

Let's say that I have a tiny code like this:

#!/usr/bin/env python3

class Dog():

  def __init__(self, name, age):
    self.name = name
    self.age = age

  def sit(self):
    print(self.name + " is now sitting.")

my_dog = Dog('willie',6)
my_dog.sit()

As I understand, the line my_dog = Dog('willie',6) creates an instance named my_dog. It calls the __init__ function, converts it internally to Dog.__init__(my_dog, willie, 6) and sets the my_dog.name and my_dog.age variables to willie and 6? Now when the my_dog.sit() is executed, then why does the method sit() require a self as a parameter? Is it because if there is another instance of the same class(for example, your_dog), then it knows to use your_dog.name instead of my_dog.name?

Martin
  • 957
  • 7
  • 25
  • 38
  • 3
    Because Python does not introduce names into scopes except when invited. – Dan D. Jan 24 '19 at 10:39
  • This article may be instructive: https://realpython.com/instance-class-and-static-methods-demystified/ In section "Instance Method", you'll find the answer to your question. – normanius Jan 24 '19 at 10:42

3 Answers3

1

"Self" signifies an instance of a class. Whenever a new instance of a class is created, "self" indicates that it will have its own variables that aren't shared with other instances. In your example, when an instance of school is made, that particular instance is referenced, it will have its own age and name variables, separate from any other school instance that may be created.

Basically, it's the opposite of a global variable. A "self" variable can only be directly used by a specific instance, rather than any thing else. If you want to use those variables, you have to clarify by using dot notation, e.g. school_one.age, school_two.name, etc.

Anonymous
  • 659
  • 6
  • 16
1

First of all, Python does not have the the offical syntax of instance variable.

When you call a method of an instance, Python will automatically insert the instance to the first argument. So, you need pass at least one argument to the method. (It's can be self, this or anything)

Chien Nguyen
  • 648
  • 5
  • 7
1

Self refers to the instance which called the method. If a function does not require self, that implies the function does not need an instance of that certain class to call the method.

mayankmehtani
  • 435
  • 4
  • 14