类的示例代码
创建类:
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 26 09:49:34 2019
@author: cenxi
"""
#python3--类
#创建类及类中的属性和方法
#python中默认首字母大写为类名,小写为类的实例
#self为形参,仅在类方法中使用,指向类的实例本身的引用,使其能够访问类中属性和方法
#调用类中方法时,参数自动传入self
class User():
def __init__(self,first_name,last_name):
self.first_name=first_name
self.last_name=last_name
self.login_attempts=0
def describe_user(self):
print("The user's firt name is "+self.first_name+" and the last name is "+self.last_name)
def greet_user(self):
print("Welcome the user "+self.last_name+" to learn python")
#通过方法修改属性值
def increment_login_attempts(self,act_login_attempts):
self.login_attempts=act_login_attempts+1
return self.login_attempts
def reset_login_attempts(self):
self.login_attempts=0
#创建多个类的实例
#调用类中的方法
user_cen=User('xi','cen')
user_cen.describe_user()
times=user_cen.increment_login_attempts(5)
print("The user has logined %d times"%times)
user_cen.greet_user()
print("-------------------------------------------------------------------------")
user_song=User('xuan','song')
user_song.describe_user()
times=user_song.increment_login_attempts(8)
print("The user has logined %d times"%times)
user_song.greet_user()
类的继承:
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 26 10:43:32 2019
@author: cenxi
"""
#类的继承
#父类
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
#类中可直接设置属性默认值,无需包含提供初始值的形参
self.odometer_reading=0
def get_descriptive_name(self):
long_name=str(self.year)+' '+self.make+' '+self.model
return long_name.title()
def read_odometer(self):
print("This car has "+str(self.odometer_reading)+" miles on it.")
def updata_odometer(self,mileage):
if mileage>=self.odometer_reading:
self.odometer_reading=mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
self.odometer_reading+=miles
def fill_gas_tank(self):
return None
#子类
#创建子类时,父类必须包含在当前文件中,且位于子类前面。
#继承时必须在括号中指定父类名称
class ElectricCar(Car):
def __init__(self,make,model,year):
#使用super()继承父类
#初始化父类属性
super().__init__(make,model,year)
#定义子类中新方法和属性
self.battery_size=70
def describe_battery(self):
print("This car has a "+str(self.battery_size)+" -kwh battery.")
#父类方法重写
def fill_gas_tank(self):
print("This car doosn't need a gas tank!")
my_tesla=ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()
参考书籍
《Python编程:从入门到实践》埃里克.马瑟斯 著