hi,
why in the definition of class class Jedi:
we don’t input the arguement as
class Jedi(name):
but we wait for the class constructor just to define the inpuit (name)
as def __init__(self,name):
till we can say j1 = Jedi('ObiWan')
, and since we already defining all the methods inside the same class, why should we put everytime (self ) ?
Let’s say you define a class like:
class Jedi(Warrior):
def init(self, name)
In this case, Warrior is the parent class that we inherit from. See:
So when:
j1 = Jedi(‘ObiWan’)
Then Warrior is the parent class of Jedi and ‘ObiWan’ is the name of the Jedi j1.
ok , and in
def say_hi(self):
print('Hello, my name is ', self.jedi_name)
why can’t we use just name instead of ```
self.jedi_name
Hi @sumerfat,
the reason why you call self.jedi_name
is that the jedi_name is defined inside the class.
If you just call jedi_name
(you can try it), it will complain that the variable does not exist. Functions can only access variables that are either defined in itself or functions defined globally (outside of the Class definition)
Let’s analyze the Dog class defined below:
#! /usr/bin/env python
name = 'Outsider Dog'
class Dog:
name = 'Inside Dog'
surname = 'Dog Surname'
def bark(self):
print('\n I am barking')
def print_name(self):
print('\n print_name called')
print('%s AND %s' % (name, self.name))
def print_surname(self):
print('\n print_surname called')
print(surname)
How would you call the bark
method?
You would first have to define the dog variable.
dog = Dog()
dog.bark()
If we call the print_name
method, you can see the difference between name
and self.name
dog = Dog()
dog.print_name()
dog.print_surname()
The messages printed (when we call the script with the code of the Dog class) show the differences between using and not using self
.
I am barking
print_name called
Outsider Dog AND Inside Dogprint_surname called
Traceback (most recent call last):
File “test.py”, line 27, in
dog.print_surname()
File “test.py”, line 19, in print_surname
print(surname)
NameError: name ‘surname’ is not defined