首页 > 代码库 > python学习笔记(5)—— class
python学习笔记(5)—— class
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 = namezebra = 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.agehippo = 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 = side110 self.side2 = side211 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 = hours14 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 = hours14 return 12*hours15 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 Falsemilton = 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 True10 else:11 return False12 13 class Equilateral(Triangle):14 angle = 6015 def __init__(self):16 self.angle1 = self.angle17 self.angle2 = self.angle18 self.angle3 = self.angle19 my_triangle = Triangle(60,60,60)20 print my_triangle.number_of_sides21 print my_triangle.check_angles()
python学习笔记(5)—— class
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。