pyton class code example

Example 1: python classes

class Box(object): #(object) ending not required
  def __init__(self, color, width, height): # Constructor: These parameters will be used upon class calling(Except self)
    self.color = color # self refers to global variables that can only be used throughout the class
    self.width = width
    self.height = height
    self.area = width * height
  def writeAboutBox(self): # self is almost always required for a function in a class, unless you don't want to use any of the global class variables
    print(f"I'm a box with the area of {self.area}, and a color of: {self.color}!")

greenSquare = Box("green", 10, 10) #Creates new square
greenSquare.writeAboutBox() # Calls writeAboutBox function of greenSquare object

Example 2: python class

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def myfunc(self):
    print("Hello my name is " + self.name +".")

p1 = Person("Victor", 24)
p1.myfunc()

Example 3: python class

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

    def speak(self):
        print("Hi I'm ", self.name, 'and I am', self.age, 'Years Old')

JUB0T = Dog('JUB0T', 55)
Friend = Dog('Doge', 10)
JUB0T.speak()
Friend.speak()

Example 4: 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)

Tags:

Lua Example