python create class example
Example 1: python class
class Animal(object): # Doesn't need params but put it there anyways.
def __init__(self, species, price):
self.species = species # Sets species name
self.price = price # Sets price of it
def overview(self): # A function that uses the params of the __init__ function
print(f"This species is called a {self.species} and the price for it is {self.price}")
class Fish(Animal): # Inherits from Animal
pass # Don't need to add anything because it's inherited everything from Animal
salmon = Fish("Salmon", "$20") # Make a object from class Fish
salmon.overview() # Run a function with it
dog = Animal("Golden retriever", "$400") # Make a object from class Animal
dog.overview() # Run a function with it
Example 2: how to declare a class in python
class ClassName(object): #"(object)" isn't mandatory unless this class inherit from another
def __init__(self, var1=0, var2):
#the name of the construct must be "__init__" or it won't work
#the arguments "self" is mandatory but you can add more if you want
self.age = var1
self.name = var2
#the construct will be execute when you declare an instance of this class
def otherFunction(self):
#the other one work like any basic fonction but in every methods,
#the first argument (here "self") return to the class in which you are