python function class code example

Example 1: how to make a class in python

class Person:
  def __init__(self, _name, _age):
    self.name = _name
    self.age = _age
   
  def sayHi(self):
    print('Hello, my name is ' + self.name + ' and I am ' + self.age + ' years old!')
    
p1 = Person('Bob', 25)
p1.sayHi() # Prints: Hello, my name is Bob and I am 25 years old!

Example 2: python define class

class uneclasse():
  def __init__(self):
    pass
  def something(self):
    pass
xx = uneclasse()
xx.something()

Example 3: 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 4: class methods in python

from datetime import date

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

    @classmethod
    def fromBirthYear(cls, name, birthYear):
        return cls(name, date.today().year - birthYear)

    def display(self):
        print(self.name + "'s age is: " + str(self.age))

person = Person('Adam', 19)
person.display()

person1 = Person.fromBirthYear('John',  1985)
person1.display()

Example 5: class in python

class ComplexNumber:
    def __init__(self, r=0, i=0):
        self.real = r
        self.imag = i

    def get_data(self):
        print(f'{self.real}+{self.imag}j')


# Create a new ComplexNumber object
num1 = ComplexNumber(2, 3)

# Call get_data() method
# Output: 2+3j
num1.get_data()

# Create another ComplexNumber object
# and create a new attribute 'attr'
num2 = ComplexNumber(5)
num2.attr = 10

# Output: (5, 0, 10)
print((num2.real, num2.imag, num2.attr))

# but c1 object doesn't have attribute 'attr'
# AttributeError: 'ComplexNumber' object has no attribute 'attr'
print(num1.attr)