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)
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:
def init(self, name)
In this case, Warrior is the parent class that we inherit from. See:
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 ```
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
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
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
I am barking
Outsider Dog AND Inside Dog
Traceback (most recent call last):
File “test.py”, line 27, in
File “test.py”, line 19, in print_surname
NameError: name ‘surname’ is not defined