class NameOfClass:
To create an instance and store it in a variable:
class Pokemon:
name = "squirtle"
pokemon = Pokemon()
To access a class variable:
print(variable.instance)
class Virtual_Pet:
wagging_tail = True
color = "brown"
skippy = Virtual_Pet()
print(skippy.wagging_tail)
Output: True
another example:
class Pokemon:
name = "squirtle"
weight = "19.8"
pokemon = Pokemon()
print(pokemon.name)
print(pokemon.weight)
Output:
squirtle
19.8
For example:
class Virtual_Pet:
color = "brown"
def bark(self):
print("Bark")
rocky = Virtual_Pet()
rocky.bark()
We use 'self' as a parameter in class methods so that we can access the class variables inside methods.
For example:
class Virtual_Pet:
color = "brown"
legs = 4
def bark(self):
print("Bark")
def display_color(self):
print(self.color)
def display_legs(self):
print(self.legs)
rocky = Virtual_Pet()
rocky.display.color()
rocky.display.legs()
Output:
brown
4
If we don't use 'self', we cannot access the class variables because they are declared outside of the class method's scope.
To use a class method:
variable.method()
For example:
class Virtual_Pet:
color = "brown"
def bark(self):
print("Bark")
rocky = Virtual_Pet()
print(rocky.color)
rocky.bark()
Output:
brown
Bark
Access and call the method 'introduce' using the class instance 'pikachu':
class Pokemon:
name = "pikachu"
def introduce(self)
print("Hi!")
print("I am " + self.name)
pikachu = Pokemon()
pikachu.introduce()
Output:
Hi!
I am pikachu
Display pikachu's color variable in the console:
class Pokemon:
name = "pikachu"
color = "yellow"
def introduce(self)
print("Hi!")
print("I am " + self.name)
pikachu = Pokemon()
pikachu.introduce()
print(pikachu.color)
Output:
Hi!
I am pikachu
yellow