1class Dog:
2
3 def bark(self):
4 print("Woof!")
5
6 def roll(self):
7 print("*rolling*")
8
9 def greet(self):
10 print("Greetings, master")
11
12 def speak(self):
13 print("I cannot!")
14
15# Creating the Dog class instance and saving it to the variable <clyde>
16clyde = Dog()
17clyde.bark() # --> Woof!
18clyde.roll() # --> *rolling*
19clyde.greet() # --> Greetings, master
20clyde.speak() # --> I cannot!
21
22# Creating another Dog instance
23jenkins = Dog()
24jenkins.bark() # --> Woof!
25jenkins.roll() # --> *rolling*
26# .. And other methods
27# .. Infinite objects can be created this way, all implementing the same methods defined in our class
28
1class Mammal:
2 def __init__(self, name):
3 self.name = name
4
5 def walk(self):
6 print(self.name + " is going for a walk")
7
8
9class Dog(Mammal):
10 def bark(self):
11 print("bark!")
12
13
14class Cat(Mammal):
15 def meow(self):
16 print("meow!")
17
18
19dog1 = Dog("Spot")
20dog1.walk()
21dog1.bark()
22cat1 = Cat("Juniper")
23cat1.walk()
24cat1.meow()
1class Person:
2 def __init__(self, _name, _age):
3 self.name = _name
4 self.age = _age
5
6 def sayHi(self):
7 print('Hello, my name is ' + self.name + ' and I am ' + self.age + ' years old!')
8
9p1 = Person('Bob', 25)
10p1.sayHi() # Prints: Hello, my name is Bob and I am 25 years old!
1# To create a simple class:
2class Shape:
3 def __init__():
4 print("A new shape has been created!")
5 pass
6
7 def get_area(self):
8 pass
9
10# To create a class that uses inheritance and polymorphism
11# from another class:
12class Rectangle(Shape):
13
14 def __init__(self, height, width): # The constructor
15 super.__init__()
16 self.height = height
17 self.width = width
18
19 def get_area(self):
20 return self.height * self.width
21
1
2class Box(object): #(object) ending not required
3 def __init__(self, color, width, height): # Constructor: These parameters will be used upon class calling(Except self)
4 self.color = color # self refers to global variables that can only be used throughout the class
5 self.width = width
6 self.height = height
7 self.area = width * height
8 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
9 print(f"I'm a box with the area of {self.area}, and a color of: {self.color}!")
10
11greenSquare = Box("green", 10, 10) #Creates new square
12greenSquare.writeAboutBox() # Calls writeAboutBox function of greenSquare object
1class Student:
2 def __init__(self, id, name, age):
3 self.name = name
4 self.id = id
5 self.age = age
6
7 def greet(self):
8 print(f"Hello there.\nMy name is {self.name}")
9
10 def get_age(self):
11 print(f"I am {self.age}")
12
13 def __add__(self, other)
14 return Student(
15 self.name+" "+other.name,
16 self.id + " "+ other.id,
17 str(self.age) +" "+str(other.age))
18
19p1 = Student(1, "Jay", 19)
20p2 = Student(2, "Jean", 22)
21p3 = Student(3, "Shanna", 32)
22p4 = Student(4, "Kayla", 23)
23
24
25result = p1+p3