python use class code example

Example 1: class python

class MyClass(object):
  def __init__(self, x):
    self.x = x

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

Example 3: classes in python

class Person:
  def __init__(self, name, age):
    
  self.name = name
    self.age = age

p1 = Person("John", 
  36)

  
print(p1.name)
print(p1.age)

Example 4: how to use class's in python

class person:
    name = "jake"
    age = 13
x = vars(person)
print(x)

Tags:

Java Example