class function python 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: class python
class MyClass(object):
def __init__(self, x):
self.x = x
Example 5: class in python
class LuckyLemur():
def __init__(self, description):
self.description = description
def reveal_description(self):
print(f'Lucky Lemur is {self.description}')
lucky_lemur = LuckyLemur('Pro')
lucky_lemur.reveal_description()
Example 6: 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()