Object-Oriented Programming
Class class
class Orange:
def __init__(self,w,c):
self.weight = w
self.color = c
print("Created!")
orl = Orange(10,"dark orange")
print(orl.color)
print(orl.weight)
class Orange:
def __init__(self,w,c):
self.weight = w
self.color = c
print("Created!")
orl = Orange(10,"dark orange")
orl = Orange(8,"light orange")
orl = Orange(6,"yellow orange")
>>>
Created!
Created!
Created!
Oranges will rot
class Orange():
def __init__(self,w,c):
self.weight = w
self.color = c
self.mold = 0
print("Created!")
def rot(self,days,temp):
self.mold = days * temp
orange = Orange(6,"yellow")
print(orange.mold)
orange.rot(10,98)
print(orange.mold)
Calculation area of a rectangle
class Rectangle():
def __init__(self,w,l):
self.width = w
self.len = l
def area(self):
return self.width * self.len
def change_size(self,w,l):
self.width = w
self.len = l
rectangle = Rectangle(10,20)
print(rectangle.area())
rectangle.change_size(20,40)
print(rectangle.area())
Exercise Challenge
1. The definition of a class called Apple to create four instance variables that Apple's four kinds of attributes.
class Apple():
def __init__(self,w,v,c,f):
self.weight = w
self.volume = v
self.color = c
self.feel = f
apple = Apple(8,2,"red","good")
print(apple.weight)
print(apple.volume)
print(apple.color)
print(apple.feel)
2. The definition of a class called Circle, create area method to calculate its area. Then create a Circle
object, call its area method, print the results. Python using the built-in module pi math functions.
import math
class Circle():
def __init__(self,r):
self.round = r
def area(self):
return math.pi * r * r
r = int(input("请输入半径:"))
circle = Circle(r)
print(circle.area())
3. The definition of a class called Triangle, create a method to calculate area and returns the area. Then create a
Triangle object, call its area method, print the results.
class Triangle():
def __init__(self,w,l):
self.width = w
self.length = l
def area(self):
return w * l
w = int(input("请输入宽度:"))
l = int(input("请输入长度:"))
triangle = Triangle(w,l)
print(triangle.area())
4. Hexagon define a called class methods create cacculate_perimeter, computes and returns
its circumference. Then create a Hexagon object, call its calculate_perimeter method, and hit
print results.
class Hexagon():
def __init__(self,w,l):
self.width = w
self.length = l
def calculate_perimeter(self):
return (self.width + self.length ) * 2
hexagon = Hexagon(20,30)
print(hexagon.calculate_perimeter())