class python 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: declare class python
# To create a simple class:
class Shape:
def __init__():
print("A new shape has been created!")
pass
def get_area(self):
pass
# To create a class that uses inheritance and polymorphism
# from another class:
class Rectangle(Shape):
def __init__(self, height, width): # The constructor
super.__init__()
self.height = height
self.width = width
def get_area(self):
return self.height * self.width
Example 3: 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 4: class python
class MyClass(object):
def __init__(self, x):
self.x = x
Example 5: class python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
p1.age = 40
print(p1.age)
---------------------------------------------------------------
40
Example 6: class python example
# If questions ask SK3#3160 he can help you i think
def ok(index):
print(index) > Hi!
ok("Hi!")
class Lib:
def ok(self,Token):
print(Token) > Hello World!
Library = Lib()
Library.ok("Hello World!")