python create 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: create and use python classes
class Mammal:
def __init__(self, name):
self.name = name
def walk(self):
print(self.name + " is going for a walk")
class Dog(Mammal):
def bark(self):
print("bark!")
class Cat(Mammal):
def meow(self):
print("meow!")
dog1 = Dog("Spot")
dog1.walk()
dog1.bark()
cat1 = Cat("Juniper")
cat1.walk()
cat1.meow()
Example 3: 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 4: python define class
class uneclasse():
def __init__(self):
pass
def something(self):
pass
xx = uneclasse()
xx.something()
Example 5: 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 6: python class
class Person:#set name of class to call it
def __init__(self, name, age):#func set ver
self.name = name#set name
self.age = age#set age
def myfunc(self):#func inside of class
print("Hello my name is " + self.name)# code that the func dose
p1 = Person("barry", 50)# setting a ver fo rthe class
p1.myfunc() #call the func and whitch ver you want it to be with