class in python example
Example 1: 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 2: python classes
class Box(object):
def __init__(self, color, width, height):
self.color = color
self.width = width
self.height = height
self.area = width * height
def writeAboutBox(self):
print(f"I'm a box with the area of {self.area}, and a color of: {self.color}!")
greenSquare = Box("green", 10, 10)
greenSquare.writeAboutBox()
Example 3: classes in python
class Foo:
def __init__(self):
self.definition = Foo!
def hi():
Example 4: classes in python
class Person():
alive = True
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print(f'Hello, my name is {self.name} and my age is {self.age}')
person_one = Person('Sam', 23)
person_one.speak()
==================================================================
>>> 'Hello, my name is Sam and my age is 23'
Example 5: class methods in python
@classmethod
def func(cls, args...)