1、空class,占空间
1 class Animal(object): 2 pass
2、定义__init__()空
1 class Animal(object): 2 def __init__(): 3 pass
3、declare name
class Animal(object): def __init__(self,name): self.name = name zebra = Animal(‘Jeffrey‘) print zebra.name #Jeffrey
4、another def
class Animal(object): """Makes cute animals.""" is_alive = True def __init__(self, name, age): self.name = name self.age = age # Add your method here! def description(self): print self.name print self.age hippo = Animal(‘aa‘,3).description() #aa #3
5、继承
1 class Shape(object): 2 """Makes shapes!""" 3 def __init__(self, number_of_sides): 4 self.number_of_sides = number_of_sides 5 6 # Add your Triangle class below! 7 class Triangle(Shape): 8 def __init__(self,side1,side2,side3): 9 self.side1 = side1 10 self.side2 = side2 11 self.side3 = side3
6、继承.复写
1 class Employee(object): 2 """Models real-life employees!""" 3 def __init__(self, employee_name): 4 self.employee_name = employee_name 5 6 def calculate_wage(self, hours): 7 self.hours = hours 8 return hours * 20.00 9 10 # Add your code below! 11 class PartTimeEmployee(Employee): 12 def calculate_wage(self,hours): 13 self.hours = hours 14 return 12*hours
7、super class
1 class Employee(object): 2 """Models real-life employees!""" 3 def __init__(self, employee_name): 4 self.employee_name = employee_name 5 6 def calculate_wage(self, hours): 7 self.hours = hours 8 return hours * 20.00 9 10 # Add your code below! 11 class PartTimeEmployee(Employee): 12 def calculate_wage(self,hours): 13 self.hours = hours 14 return 12*hours 15 def full_time_wage(self,hours): 16 return super(PartTimeEmployee,self).calculate_wage(hours)#返回父class函数 17 18 milton = PartTimeEmployee(‘aa‘) 19 print milton.full_time_wage(10) 20 #200
Example
class Triangle(object): number_of_sides = 3 def __init__(self,angle1,angle2,angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 def check_angles(self): if self.angle1+self.angle2+self.angle3 == 180: return True else: return False milton = Triangle(60,60,60) print milton.check_angles() #True
1 class Triangle(object): 2 number_of_sides = 3 3 def __init__(self,angle1,angle2,angle3): 4 self.angle1 = angle1 5 self.angle2 = angle2 6 self.angle3 = angle3 7 def check_angles(self): 8 if self.angle1+self.angle2+self.angle3 == 180: 9 return True 10 else: 11 return False 12 13 class Equilateral(Triangle): 14 angle = 60 15 def __init__(self): 16 self.angle1 = self.angle 17 self.angle2 = self.angle 18 self.angle3 = self.angle 19 my_triangle = Triangle(60,60,60) 20 print my_triangle.number_of_sides 21 print my_triangle.check_angles()
时间: 2024-11-10 07:04:23