Why is self a required parameter for a method? [duplicate] - python

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 4 years ago.
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?

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)

"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.

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.

Related

How does the "self" work in this python code [duplicate]

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed last year.
Have two simple python codes, both are working. But no sure what is the "self" in there that makes the difference. When to use and when not to use "self"?
class car:
colour="red"
def method1():
print("method1")
myCar=car
myCar.method1()
class car:
colour="red"
def method1(self):
print("method1")
myCar=car()
myCar.method1()
In the first snippet, myCar refers to the class car, and method1 appears to be being used as a static method of that class.
In the second snippet, myCar refers to an instance of the class car, and method1 is an instance method -- the typical usage. Instance methods receive as a first argument the instance calling the method.
Conceptually, the difference is that in the second snippet you're referring to a car and in the first snippet you're referring to the concept of cars in general.

why do we pass self on all class methods? [duplicate]

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 1 year ago.
I know that some of you will think It's a stupid question but I will ask anyway.
why do we need to pass 'self' on all class methods can't we use it without passing it like this:
class Player:
def __init__(name):
self.name = name
def print_player_name():
print(self.name)
Try it. It won't work because self is not defined. The name "self" is just established, but you could name it whatever you want. It refers to the object of the class on which the method is called.
Yes, you can do it but you have to mention it as a static method. Self represents the instance of the class. In simple words, self represents the object on which it is being executed. When you create an object, all variables change their values based on different object of same class. Every class needs object as it's argument because for different object, different values are assigned
self represents object of class on which method is called you don't always need to name it self[standard convention] any valid variable name is allowed in python to do this but it should be first argument of non-classmethods and should be replace self as in if you run this python will work as expected :
class Player:
def __init__(hello, name):
hello.name = name
def print_player_name(hello):
print(hello.name)
It's very simple that's the official Python convention. In official docs we can read about it.
"Often, the first argument of a method is called self. This is nothing
more than a convention: the name self has absolutely no special
meaning to Python. Note, however, that by not following the convention
your code may be less readable to other Python programmers, and it is
also conceivable that a class browser program might be written that
relies upon such a convention."

Python inheritance: when and why __init__

I'm a Python newbie, trying to understand the philosophy/logic behind the inheritance methods. Questions ultimately regards why and when one has to use the __init__ method in a subclass. Example:
It seems a subclass inheriting from a superclass need not have its own constructor (__init__) method. Below, a dog inherits the attributes (name, age) and methods (makenoise) of a mammal. You can even add a method (do_a_trick) Everything works as it ``should", it seems.
However, if I wanted to add a new attribute in the subclass as I attempt to do in the Cats class, I get an error saying "self" is not defined. Yet I used "self" in the definition of the dog class. What's the nature of the difference?
It seems to define Cats as I wish I need to use __init__(self,name) and super()__init__(name). Why the difference?
class Mammals(object):
def __init__(self,name):
self.name = name
print("I am a new-born "+ self.name)
self.age = 0
def makenoise(self):
print(self.name + " says Hello")
class Dogs(Mammals):
def do_a_trick(self):
print(self.name + " can roll over")
class Cats(Mammals):
self.furry = "True" #results in error `self' is not defined
mymammal = Mammals("zebra") #output "I am a new-born zebra"
mymammal.makenoise() #output "zebra says hello"
print(mymmmal.age) #output 0
mydog = Dogs("family pet") #output "I am a new-born family pet"
mydog.makenoise() #output "family pet says hello"
print(mydog.age) # output 0
mydog.do_a_trick() #output "family pet can roll over"
Explicit is better than implicit.
However, you can do below:
class Dogs(Mammals):
def __init__(self):
#add new attribute
self.someattribute = 'value'
Mammals.__init__(self)
or
class Dogs(Mammals):
def __init__(self):
#add new attribute
self.someattribute = 'value'
super(Mammals, self).__init__()
if I wanted to add a new attribute in the subclass as I attempt to do
in the Cats class, I get an error saying "self" is not defined. Yet I
used "self" in the definition of the dog class.
In your superclass, Mammal, you have an __init__ function, which takes an argument that you've chosen* to call self. This argument is in scope when you're in the body of the __init__ function - it's a local variable like any local variable, and it's not possible to refer to it after its containing function terminates.
The function defined on the Dog class, do_a_trick, also takes an argument called self, and it is also local to that function.
What makes these variables special is not their name (you could call them anything you wanted) but the fact that, as the first arguments to instance methods in python, they get a reference to the object on which they're called as their value. (Read that last sentence again a few times, it's the key to understanding this, and you probably won't get it the first time.)
Now, in Cat, you have a line of code which is not in a function at all. Nothing is in scope at this point, including self, which is why this fails. If you were to define a function in Cat that took an argument called self, it would be possible to refer to that argument. If that argument happened to be the first argument to an instance method on Cat, then it would have the value of the instance of Cat on which it had been called. Otherwise, it would have whatever got passed to it.
*you have chosen wisely!
Declarations at the top level of a Python class become class attributes. If you come from a C++ or Java background, this is similar to declaring a static member variable. You cannot assign instance attributes at that level.
The variable self usually refers to a specific instance of a class, the one from which the method has been called. When a method call is made using the syntax inst.method(), the first argument to the function is the object inst on which the method was called. In your case, and usually by convention, that argument is named self within the function body of methods. You can think of self as only being a valid identifier within method bodies then. Your assignment self.furry = True does not take place in a method, so self isn't defined there.
You have basically two options for achieving what you want. The first is to properly define furry as an attribute of the cat class:
class Cat(Mammals):
furry = True
# Rest of Cat implementation ...
or you can set the value of an instance variable furry in the cat constructor:
class Cat(Mammals):
def __init__(self):
super(Mammals, self).__init__(self)
self.furry = True
# Rest of Cat implementation ...
If you're getting into Python I highly recommend to read these two parts of the Python documentation:
Python classes
Python data model special methods (more advanced)
As pointed out in the other answers, the self that you see in the other
functions is actually a parameter. By Python convention, the first parameter in
an instance method is always self.
The class Cats inherits the __init__ function from its base class,
Mammals. You can override __init__, and you can call or not call the base
class implementation.
In case the Cats __init__ wants to call the base implementation, but doesn't want to care about the parameters, you can use Python variable arguments. This is shown in the following code.
Class declaration:
class Cats(Mammals):
def __init__(self, *args):
super().__init__(*args)
self.furry = "True"
See, for example, this Stack Overflow question for something about the star
notation for variable numbers of arguments:
Can a variable number of arguments be passed to a function?
Additional test code:
cat = Cats("cat")
print(vars(cat))
Output:
I am a new-born cat
{'name': 'cat', 'age': 0, 'furry': 'True'}
You can do something like in Chankey's answer by initiating all the variables in the constructor method ie __init__
However you can also do something like this
class Cats(Mammals):
furry = "True"
And then
cat = Cats("Tom")
cat.furry # Returns "True"
The reason you can't use self outside the functions is because self is used explicitly only for instances of the class. If you used it outside, it would lead to ambiguity. If my answer isn't clear please let me know in comments.
The __init__ method runs once on the creation of an instance of a class. So if you want to set an attribute on an instance when it's created, that's where you do it. self is a special keyword that is passed as the first argument to every method, and it refers to the instance itself. __init__ is no different from other methods in this regard.
"What's the nature of the difference": you define the method Dog.do_a_trick, and you receive self as an argument to the method as usual. But in Cat you've unintentionally (perhaps subconsciously!) attempted to work on the class scope -- this is how you'd set a class attribute whose value is identical for all cats:
class Cat(object):
sound = "meow"
It's different so you can have both options available. Sometimes (not all the time, but once in a while) a class attribute is a useful thing to have. All cats have the same sound. But much of the time you'll work with instance attributes -- different cats have different names; when you need that, use __init__.
Suppose you have a class named Person which has a method named get_name defined as :
class Person():
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def get_name(self):
return self.first_name + ' ' + self.last_name
And, you create an instance of Person as p1. Now when you call the function get_name() with this instance, it will converts internally
Person.get_name(p1)
So, self is the instance itself.
Without self you can write above code as :
class Person():
first_name = None
last_name = None
def get_name(personobject):
return personobject.first_name + ' ' + personobject.last_name
What I am trying to say is the name self is a convention only.
And for inheritance, if you would like to have extra attributes in your subclass, you need to initiate your super class first and add your parameter as you wanted.
For example, if you want to create a subclass from Person named Boy with new attribute height, the you can define it as:
class Boy(Person):
def __init__(self, first_name, last_name, height):
super(Person, self).__init__(first_name, last_name)
self.height = height

How access variables inside method? (python) [duplicate]

This question already has answers here:
Python class attribute referencing
(2 answers)
Closed 7 years ago.
Is it possible to access self.bin outside the class?
class kon():
def __init__(self):
pass
def add(self):
con=7
self.bin=100
h=kon()
bin=h.bin
In one topic advised to use self. before variables but it did not work.
Maybe such variables must be in __init__ method.
You have to read docs. It will be very useful for you.
The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named init(), like this:
def __init__(self):
self.bin = 0
When a class defines an init() method, class instantiation automatically invokes init() for the newly-created class instance.
After this you can use this property in you object, to read or assign value.
Also, there is a difference between initialize properties in the class. From the docs:
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance

Difference between methods and member variables?

class Animal(object):
"""Makes cute animals."""
is_alive = True
health = 'good'
def __init__(self, name, age):
self.name = name
self.age = age
# Add your method here!
def description(self):
print self.name
print self.age
hippo = Animal('Tom', '20')
sloth = Animal('Randy', '18')
ocelot = Animal('Birdman','57')
hippo.description()
print ocelot.health
print hippo.health
print sloth.health
The code above is from codecademy's python course. I am getting confused about some of the definitions surrounding OOP. If my understanding is correct, a function defined within a class is known as a method, which is why when it's called, for example like this: 'hippo.description()', the '()' are necessary because of the syntax involving functions.
However, I start to get confused with 'self.name' and 'self.age'. Are these also methods? I was wondering if they were perhaps member variables, but then wouldn't they be defined in the same way the variable 'health' was above? And if they aren't member variables, how come they can be accessed using dot notation in the same way as the member variables?
Cheers
I assume you're coming from a more traditional OOP programming language like C++ or Java.
health in the Animal class is what you would refer to as a static member variable, but in Python this is called a class attribute because it is unique to the class.
name in the Animal class is what you would refer to as a member or instance variable, and in Python this is called an instance attribute because it is unique to each instance of a class.
You use self to refer to attributes within its own class.
First of all the difference between class and instance attributes are answered elsewhere.
The difference between a method and member variables are that while they are both attributes, a method is a function while a member variable is not (or need not be). Also a method is normally a class attribute (at least if you use new style classes).
However in python functions are first class objects so this may confuse a little more: it's perfectly valid to assign a member variable with a function (or vice versa), but then that will become somewhat different because normally a method is shared among all objects, but when assigned to an instance it becomes private to that instance.
self.foo may be used to access both instance attributes or class attributes (if instance attribute does not exist).

Categories