python classes functions methods code example

Example 1: call instance class python

# define class
class example:
# define __call__ function
   def __call__(self):
       print("It worked!")
# create instance
g = example()
# when attempting to call instance of class it will call the __class method
g()
# prints It worked!

Example 2: 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

Tags:

Misc Example