码迷,mamicode.com
首页 > 编程语言 > 详细

Python编程入门到实践 - 笔记( 9 章)

时间:2017-09-15 18:56:43      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:python类


第 9 章主要讲的类,这个之前在 shell 中没遇到过

一直运用的也不是很溜,不过多敲多练,应该会有进步吧


创建类和使用类

创建一个 Dog 类

---------------------------------------------------------------------

class Dog():    
     def __init__(self, name, age):    
          self.name = name    
          self.age = age    
     def sit(self):    
          print(self.name.title() + " is now sitting.")    
     def roll_over(self):    
          print(self.name.title() + " rolled over!")

my_dog = Dog(‘willie‘, 6)    
my_dog.sit()    
my_dog.roll_over()  

   

print("My dog‘s name is " + my_dog.name.title() + ".")    
print("My dog is " + str(my_dog.age) + " years old.")

------------------------------------------------------------------------

Willie is now sitting.    
Willie rolled over!    
My dog‘s name is Willie.    
My dog is 6 years old.



创建多个实例

------------------------------------------------------------------------------

class Dog():    
     def __init__(self, name, age):    
          self.name = name    
          self.age = age    
     def sit(self):    
          print(self.name.title() + " is now sitting.")    
     def roll_over(self):    
          print(self.name.title() + " rolled over!")

my_dog = Dog(‘willie‘, 6)    
your_dog = Dog(‘lucy‘, 3)


print("My dog‘s name is " + my_dog.name.title() + ".")    
print("My dog is " + str(my_dog.age) + " years old.")    
my_dog.sit()


print("\nYour dog‘s name is " + your_dog.name.title() + ".")    
print("Your dog is " + str(your_dog.age) + " years old.")    
your_dog.sit()

------------------------------------------------------------------------------

My dog‘s name is Willie.    
My dog is 6 years old.    
Willie is now sitting.


Your dog‘s name is Lucy.    
Your dog is 3 years old.    
Lucy is now sitting.



Car 类练习

------------------------------------------------------------------------------------

class Car():    
     def __init__(self, make, model, year):    
          self.make = make    
          self.model = model    
           self.year = year    
     def get_descriptive_name(self):    
          long_name = self.year + ‘ ‘ + self.make + ‘ ‘ + str(self.model)    
          return long_name.title() 

   
my_new_car = Car(‘audi‘, 24, ‘2016‘)    
print(my_new_car.get_descriptive_name())

------------------------------------------------------------------------------------

2016 Audi 24    



添加属性默认值

-------------------------------------------------------------------------------------------

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 + ‘ ‘ + str(self.model)    
          return long_name.title()

     def read_odometer(self):    
          print("This car has " + str(self.odometer_reading) + " miles on it.")

my_new_car = Car(‘audi‘, ‘24‘, ‘2016‘)    
print(my_new_car.get_descriptive_name())    
my_new_car.read_odometer()

-------------------------------------------------------------------------------------------

2016 Audi 24    
This car has 0 miles on it.



修改属性的值

-------------------------------------------------------------------------------------------

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 + ‘ ‘ + str(self.model)    
           return long_name.title()

     def read_odometer(self):    
          print("This car has " + str(self.odometer_reading) + " miles on it.")

my_new_car = Car(‘audi‘, ‘24‘, ‘2016‘)    
print(my_new_car.get_descriptive_name())    
my_new_car.odometer_reading = 23    
my_new_car.read_odometer()

-------------------------------------------------------------------------------------------

2016 Audi 24    
This car has 23 miles on it.



通过方法修改属性的值

-------------------------------------------------------------------------------------------

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 + ‘ ‘ + str(self.model)    
          return long_name.title()

     def read_odometer(self):    
          print("This car has " + str(self.odometer_reading) + " miles on it.")

     def update_odometer(self, mileage):    
          self.odometer_reading = mileage


my_new_car = Car(‘audi‘, ‘24‘, ‘2016‘)    
print(my_new_car.get_descriptive_name()) 

   
my_new_car.update_odometer(45)    
my_new_car.read_odometer()

-------------------------------------------------------------------------------------------

2016 Audi 24    


This car has 45 miles on it.   


 

通过方法对属性的值进行递增

-------------------------------------------------------------------------------------------

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 + ‘ ‘ + str(self.model)    
          return long_name.title()

     def read_odometer(self):    
          print("This car has " + str(self.odometer_reading) + " miles on it.")

     def update_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


my_used_car = Car(‘subaru‘, ‘outback‘, 2013)    
print(my_used_car.get_descriptive_name())


my_used_car.update_odometer(23500)    
my_used_car.read_odometer()

my_used_car.increment_odometer(100)    
my_used_car.read_odometer()

-------------------------------------------------------------------------------------------

2013 Subaru Outback    
This car has 23500 miles on it.    
This car has 23600 miles on it.



继承 : 子类的方法 __init__( )

父类必须包含在当前文件中,且位于子类前面

定义子类时,括号中必须指定父类的名称

super( ) 是一个特殊函数,将父类和子类关联起来,让 ElectricCar 实例包含父类的所有属性

父类也称为超类。

-------------------------------------------------------------------------------------------

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 + ‘ ‘ + str(self.model)    
          return long_name.title()

     def read_odometer(self):    
          print("This car has " + str(self.odometer_reading) + " miles on it.")

     def update_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


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_descriptive_name())

-------------------------------------------------------------------------------------------

2016 Tesla Model S



给子类定义属性和方法

-------------------------------------------------------------------------------------------

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 + ‘ ‘ + str(self.model)    
          return long_name.title()

     def read_odometer(self):  
          print("This car has " + str(self.odometer_reading) + " miles on it.")

     def update_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


class ElectricCar(Car):    
     def __init__(self, make, model, year):    
          super().__init__(make, model, year)    
          self.battery_size = 70    
     def describe_battery(self):    
          print("This car has a " + str(self.battery_size) + "-kWh battery.")


my_tesla = ElectricCar(‘tesla‘, ‘model s‘, 2016)  
print(my_tesla.get_descriptive_name())    
my_tesla.describe_battery()

-------------------------------------------------------------------------------------------

2016 Tesla Model S  
This car has a 70-kWh battery.



重写父类的方法

假设 Car 类中有一个名为 fill_gas_tank( ) 的函数,但是它对电动汽车毫无意义

可以在子类中重写该函数,Python就会运转子类中的代码,

而且还会保留父类中的其他函数

------------------------------------------------------------

def fill_gas_tank():  
         print("This car doesn‘t need a gas tank")

------------------------------------------------------------  


 

将实例用作属性

新建一个 class Battery() 的类

在 class ElectricCar(Car) 类中指定 class Battery()

-------------------------------------------------------------------------------------------

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 + ‘ ‘ + str(self.model)    
           return long_name.title()

     def read_odometer(self):  
           print("This car has " + str(self.odometer_reading) + " miles on it.")

     def update_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


class Battery():    
     def __init__(self, battery_size=70):    
          self.battery_size = battery_size    
     def 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‘, ‘year‘)


print(my_tesla.get_descriptive_name())    
my_tesla.battery.describe_battery()

-------------------------------------------------------------------------------------------

2016 Tesla Model S  
This car has a 70-kWh battery.  


  

导入单个类

my_car.py导入car.py中的 Car 类


car.py 文件内容如下

-------------------------------------------------------------------------------------------

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 + ‘ ‘ + str(self.model)    
          return long_name.title()

     def read_odometer(self):  
           print("This car has " + str(self.odometer_reading) + " miles on it.")

     def update_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

-------------------------------------------------------------------------------------------

my_car.py 文件内容如下

-----------------------------------------------------------------

from car import Car

my_new_car = Car(‘audi‘, ‘24‘, 2016)  
print(my_new_car.get_descriptive_name())

my_new_car.odometer_reading = 23



导入模块中的类

从 car.py 文件中导入 ElectricCar 类

-------------------------------------

from car import ElectricCar

-------------------------------------



导入模块中的多个类

------------------------------------------

from car import ElectricCar, Car

------------------------------------------



导入整个模块

直接导入 car.py 文件中全部函数

------------------------------------------

import car

my_beetle = car.Car(‘volkswagen’, ‘beetle’)

------------------------------------------



Python标准库

collections 模块中的 OrderedDict 类

-------------------------------------------------------------------------------------------

from collections import OrderedDict

favorite_languages = OrderedDict()

favorite_languages[‘jen‘] = ‘python‘  
favorite_languages[‘sarah‘] = ‘c‘    
favorite_languages[‘edward‘] = ‘ruby‘    
favorite_languages[‘phil‘] = ‘python‘

for name, language in favorite_languages.items():  
     print(name.title() + "‘s favorite language is " + language.title() + ".")

-------------------------------------------------------------------------------------------

Jen‘s favorite language is Python.

Sarah‘s favorite language is C.

Edward‘s favorite language is Ruby.

Phil‘s favorite language is Python.


本文出自 “LULU” 博客,请务必保留此出处http://aby028.blog.51cto.com/5371905/1965593

Python编程入门到实践 - 笔记( 9 章)

标签:python类

原文地址:http://aby028.blog.51cto.com/5371905/1965593

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!