根據Dog類別建立的每個實列都會儲存名字和年齡。我們賦予了每條小狗蹲下(sit())和打滾(roll_over())的能力:
1 class Dog(): 2 """一次模拟小狗的简单尝试""" 3 def __init__(self, name, age): 4 """初始化属性name和age""" 5 self.name = name 6 self.age = age 7 def sit(self): 8 """模拟小狗被命令时蹲下""" 9 print(self.name.title() + "now is sitting.")10 def roll_over(self):11 """模拟小狗被命令时打滚"""12 print(self.name.title() + "rolled over!")13 my_dog = Dog('tom','3')14 print("my dog name is " + my_dog.name.title() )
class Dog():"""一次模拟小狗的简单尝试"""def __init__(self, name, age):"""初始化属性name和age"""self.name = name self.age = agedef sit(self):"""模拟小狗被命令时蹲下"""print(self.name.title() + " now is sitting.")def roll_over(self):"""模拟小狗被命令时打滚"""print(self.name.title() + " rolled over!") my_dog = Dog('tom',3)print(my_dog.name)print(my_dog.age)#运行结果tom3
class Dog():"""一次模拟小狗的简单尝试"""def __init__(self, name, age):"""初始化属性name和age"""self.name = name self.age = agedef sit(self):"""模拟小狗被命令时蹲下"""print(self.name.title() + " now is sitting.")def roll_over(self):"""模拟小狗被命令时打滚"""print(self.name.title() + " rolled over!") my_dog = Dog('tom',3) my_dog.sit() my_dog.roll_over()#运行结果Tom now is sitting. Tom rolled over!根據Dog類別建立實例後,就可以使用句點表示來呼叫Dog來定義的任何方法
class Dog():"""一次模拟小狗的简单尝试"""def __init__(self, name, age):"""初始化属性name和age"""self.name = name self.age = agedef sit(self):"""模拟小狗被命令时蹲下"""print(self.name.title() + " now is sitting.")def roll_over(self):"""模拟小狗被命令时打滚"""print(self.name.title() + " rolled over!") my_dog = Dog('tom',3) your_dog = Dog('Mei',2)print("My dog name is " + my_dog.name.title())print("Your dog name is " + your_dog.name.title())#运行结果My dog name is Tom Your dog name is Mei可按需求根據類別創建任意數量的實例。
使用類別和實例
class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make
self.model = model
self.year = year
self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_name
my_car = Car('audi', 'a4', '2017')print(my_car.model)print(my_car.get_descri_name())#运行结果a42017 a4 audi
#class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make
self.model = model
self.year = year
self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_name
my_car = Car('audi', 'a4', '2017')print(my_car.get_descri_name())
my_car.year = 2016print(my_car.get_descri_name())#运行结果2017 a4 audi2016 a4 audi
class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make self.model = model self.year = year self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_namedef update(self, mile):"""更新里程值"""if mile > self.odometer_reading: self.odometer_reading = mileelse:print("You can't roll back an odometer")def increment_odometer(self,mile):"""增加里程"""self.odometer_reading += miledef read_odometer(self):"""打印汽车的里程"""print("This car has " + str(self.odometer_reading) + " miles on it.") my_car = Car('audi', 'a4', '2017') my_car.read_odometer() my_car.odometer_reading = 10 #直接修改里程值my_car.update(200) #通过方法修改里程my_car.read_odometer() my_car.increment_odometer(10) my_car.read_odometer()#运行结果This car has 100 miles on it. This car has 200 miles on it. This car has 210 miles on it.
class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make self.model = model self.year = year self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_namedef update(self, mile):"""更新里程值"""if mile > self.odometer_reading: self.odometer_reading = mileelse:print("You can't roll back an odometer")def increment_odometer(self,mile):"""增加里程"""self.odometer_reading += miledef read_odometer(self):"""打印汽车的里程"""print("This car has " + str(self.odometer_reading) + " miles on it.")class ElectricCar(Car):"""电动汽车的独特特性"""def __init__(self, make, model, year):"""初始化父类的属性"""super().__init__(make, model, year) my_tesla = ElectricCar('tesla', 'model s', '2016')print(my_tesla.get_descri_name())#运行结果2016 model s tesla
為了繼承父類別的屬性,
還需要加入一個特殊的函數super(),幫助python將夫類別和子類別關聯起來。在python2.X中,類別supper的格式如下:
supper(Eletric,self).__init__(make, model, year)#給子類別定義屬性和方法讓一個類別繼承另一個類別後,可新增區分子類別和父類別所屬的新屬性和新方法。
將實例當作屬性
class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make self.model = model self.year = year self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_namedef update(self, mile):"""更新里程值"""if mile > self.odometer_reading: self.odometer_reading = mileelse:print("You can't roll back an odometer")def increment_odometer(self,mile):"""增加里程"""self.odometer_reading += miledef read_odometer(self):"""打印汽车的里程"""print("This car has " + str(self.odometer_reading) + " miles on it.")class Battery():"""一次模拟电动汽车"""def __init__(self,battery_size=70):"""初始化电瓶的属性"""self.battery_size = battery_sizedef describe_battery(self):"""打印一条描述电瓶容量的消息"""print("This car has a " + str(self.battery_size) + "-kwh battery.")class ElectricCar(Car):"""电动汽车的独特特性"""def __init__(self, make, model, year):"""初始化父类的属性"""super().__init__(make, model, year) self.battery = Battery() my_tesla = ElectricCar('tesla', 'model s', '2016')print(my_tesla.get_descri_name()) my_tesla.battery.describe_battery()#运行结果2016 model s tesla This car has a 70-kwh battery.#
匯入類別
匯入單一或多個類別
class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make self.model = model self.year = year self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_namedef update(self, mile):"""更新里程值"""if mile > self.odometer_reading: self.odometer_reading = mileelse:print("You can't roll back an odometer")def increment_odometer(self,mile):"""增加里程"""self.odometer_reading += miledef read_odometer(self):"""打印汽车的里程"""print("This car has " + str(self.odometer_reading) + " miles on it.")class Battery():"""一次模拟电动汽车"""def __init__(self,battery_size=70):"""初始化电瓶的属性"""self.battery_size = battery_sizedef describe_battery(self):"""打印一条描述电瓶容量的消息"""print("This car has a " + str(self.battery_size) + "-kwh battery.")class ElectricCar(Car):"""电动汽车的独特特性"""def __init__(self, make, model, year):"""初始化父类的属性"""super().__init__(make, model, year) self.battery = Battery()建立另一個檔案my_car.py,匯入一個類別
from car import Car my_car = Car('audi', 'a4', '2017')一個模組中可以儲存多個類,所以可以一次導入多個類別
from car import Car,Battery,ElectricCar my_tesla = ElectricCar('tesla', 'model s', '2016')print(my_tesla.get_descri_name()) my_tesla.battery.describe_battery()
import car #导入整个模块的时候,需要使用句点表示法访问需要的类 my_tesla = car.ElectricCar('tesla', 'model s', '2016')print(my_tesla.battery)
from car import * #导入所有的类######### ###### ###### ###### ###### ###### ####### ##### ## ###### ###### ###### ####### ###### ######o####### ######### ####### ###
以上是建立一個簡單的類別的實例教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!