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
1class Employee(Object)
2 def __init__(self, name, age, salary):
3 self.name = name
4 self.age = age
5 self.salary = salary
6
7
8
9 def __str__(self)
10 return f"Employee {name} \nhes age {age} \nand make {salary}"
1class Person:
2 def __init__(self, name, age):
3 self.name = name
4 self.age = age
5
6p1 = Person("John", 36)
7
8p1.age = 40
9
10print(p1.age)
11---------------------------------------------------------------
1240
1class A: # define your class A
2.....
3
4class B: # define your class B
5.....
6
7class C(A, B): # subclass of A and B
8
9obj = C() #to create instance
10# issubclass(sub, sup) boolean function returns true if the given
11# subclass sub is indeed a subclass of the superclass sup
12
13# isinstance(obj, Class) boolean function returns true if obj is an
14# instance of class Class or is an instance of a subclass of Class
1class Charge:
2 def __init__(self, employee, discount):
3 self.employee = employee
4 self.discount = discount
5
6 def _discounted_pricey(self):
7 item_price = 100
8 discounted_price = item_price * (1-self.discount)
9 return discounted_price
10
11 def __discounted_price(self):
12 item_price = 100
13 discounted_price = item_price * (1-self.discount)
14 return discounted_price
15
16 def pays(self):
17 price_to_charge = self.__discounted_price() # gotcha: self.
18 print(f'Charge {self.employee} ${price_to_charge:.2f} ({self.discount:.2%} off)')
19
20Employee = Charge(employee='Billy Beans', discount=.1)
21
22print(Employee.employee) # Billy Beans
23print(Employee.discount) # 0.1
24print(Employee._discounted_pricey()) # 90.0
25print(Employee.__discounted_price()) # AttributeError: 'Charge' object has no attribute '__discounted_price'
26print(Employee.item_price) # AttributeError: 'Charge' object has no attribute 'item_price'
27Employee.pays() # Charge Billy Beans $90.00 (10.00% off)