self in python
"""
Before potentially reading along I highly suggest you master how to
use parameters and arguments in python because if you haven't this can
get confusing. Otherwise read along:
The self argument is most frequently used in the __init__ function.
The __init__ function is a constructor function meaning that it
constructs objects in a class.
This is part of the object oriented programming (OOP) branch.
In this example ill be creating a person with values of name, gender and
age.
What 'self' essentailly is, is the class, so when referring to 'self'
you are refering to values in a class.
So 'self.age = age' is just adding a variable in the
class which has the same value as 'age'.
"""
# Creating the class
class Person:
# Creating the constructor method
def __init__(self, name, age, male):
# defining variables
self.name = name
self.age = age
self.gender = male
# Creating Objects
Person1 = Person("Isabella", 27, False)
Person2 = Person("Mikkel", 29, True)
# (This next bit is unnecessary)
People = [ Person1, Person2 ]
"""
Thats essentially how to use constructors but for more examples I will
show you how to use them in a different way.
"""
class Person:
def __init__(self, name, age, male):
self.name = name
self.age = age
self.gender = male
def Function(self):
print(self.name)
print(self.age)
P = Person("Jeff",27)
P.Function()
# Output:
# >>> Jeff
# >>> 27
"""
This is a great example to show how self functions and how that they are
essentially the exact same as variables but instead stored inside a class
the word 'self' means the class.
So when doing 'self.something' logically you can think of it as:
'class.something'
"""
# Whoever got to the end of this insanely long grepper answer
# I wish you a wonderful day :)
By using the “self” keyword we can access the attributes
and methods of the class in python.
It binds the attributes with the given arguments.
self is parameter in function and user can use another parameter
name in place of it.
But it is advisable to use self because,
it increase the readability of code.
# Write Python3 code here
class car():
# init method or constructor
def __init__(self, model, color):
self.model = model
self.color = color
def show(self):
print("Model is", self.model )
print("color is", self.color )
# both objects have different self which
# contain their attributes
audi = car("audi a4", "blue")
ferrari = car("ferrari 488", "green")
audi.show() # same output as car.show(audi)
ferrari.show() # same output as car.show(ferrari)
# Behind the scene, in every instance method
# call, python sends the instances also with
# that method call like car.show(audi)