1 类
\面向对象编程 是最有效的软件编写方法之一
1.1 创建和使用类
1.1.1 创建Dog 类
[root@swt ~]# cat simple.py
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(selt):
print (selt.name.title() + "is now rolled over")
\\我们定义了一个名为Dog 的类。根据约定,在Python中,首字母大写的名称指的是类。这个类定义中的括号是空的,因为我们要从空白创建这个类。
\\方法__init__()
\\是一个特殊的方法,每当你根据Dog 类创建新实例时,Python都会自动运行它
\\开头和末尾各有两个下划线,这是一种约定,旨在避免Python默认方法与普通方法发生名称冲突。
1.1.2 根据类创建实例
\\用以上类
my_dog = Dog('jack',10)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years ord.")
[root@swt ~]# python3 simple.py
My dog's name is Jack.
My dog is 10 years ord.
\\调用方法
my_dog = Dog('jack',10)
my_dog.sit()
my_dog.roll_over()
[root@swt ~]# python3 simple.py
Jack is now sitting.
Jackis now rolled over
\\练一练
[root@swt ~]# cat simple.py
class Restaurant ():
def __init__(simple,restaurant_name,cuisine_type):
simple.restaurant_name=restaurant_name
simple.cuisine_type=cuisine_type
def describe_restaurant(simple):
print("The name of this restaurant is " + simple.restaurant_name.title())
print ("The typr of this restaurant is " + simple.cuisine_type.title())
def open_restaurant(simple):
print ("Opening and closing!")
restaurant = Restaurant('MacDonald', 'European food')
restaurant.describe_restaurant()
restaurant.open_restaurant()
[root@swt ~]# python3 simple.py
The name of this restaurant is Macdonald
The typr of this restaurant is European Food
Opening and closing!
\\
[root@swt ~]# cat simple.py
class User():
def __init__(simple,first_name,last_name,age,seen):
simple.first_name=first_name
simple.last_name=last_name
simple.age=age
simple.seen=seen
def describe_user(simple):
print ("The name of the user is " + simple.first_name.title() + simple.last_name.title() + ".")
print ("The age of the user is " + str(simple.age) + ".")
print ("The gender of users is " + simple.seen.title() + ".")
def greet_user(simple):
print ("Hello," + simple.first_name.title() + simple.last_name.title() + "." )
xiefei = User('xie','fei',20,'boy')
xiefei.describe_user()
xiefei.greet_user()
[root@swt ~]# python3 simple.py
The name of the user is XieFei.
The age of the user is 20.
The gender of users is Boy.
Hello,XieFei.
1.2 使用类和实例
1.2.1 Car 类
[root@swt ~]# cat simple.py
class Car():
def __init__(self, make, color, year):
self.make = make
self.color = color
self.year = year
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make.title() + ' ' + self.color.title()
return long_name
my_name_car = Car(' Perkins','red',2019)
print(my_name_car.get_descriptive_name())
[root@swt ~]# python3 simple.py
2019 Perkins Red
1.2.2 给属性指定默认值
[root@swt ~]# cat simple.py
class Car():
def __init__(self, make, color, year):
self.make = make
self.color = color
self.year = year
self.money = '4000万'
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make.title() + ' ' + self.color.title()
#long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name
def get_money(self):
print ("It costs money to buy this car " + self.money )
my_name_car = Car(' Perkins','red',2019)
print(my_name_car.get_descriptive_name())
my_name_car.get_money()
[root@swt ~]# python3 simple.py
2019 Perkins Red
It costs money to buy this car 4000万
1.2.3 修改属性的值
\\1. 直接修改属性的值
class Car():
def __init__(self, make, color, year):
self.make = make
self.color = color
self.year = year
self.money = '4000万'
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make.title() + ' ' + self.color.title()
return long_name
def get_money(self):
print ("It costs money to buy this car " + self.money )
my_name_car = Car(' Perkins','red',2019)
print(my_name_car.get_descriptive_name())
my_name_car.money = '3500万' //修改
my_name_car.get_money()
\\2. 通过方法修改属性的值
class Car():
def __init__(self, make, color, year):
self.make = make
self.color = color
self.year = year
self.money = '4000万'
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make.title() + ' ' + self.color.title()
return long_name
def get_money(self):
print ("It costs money to buy this car " + self.money )
def update_money(self,coppen):
self.money = coppen
my_name_car = Car(' Perkins','red',2019)
print(my_name_car.get_descriptive_name())
my_name_car.update_money('3500万')
my_name_car.get_money()
\\ 3. 通过方法对属性的值进行递增
[root@swt ~]# cat simple.py
class Car():
def __init__(self, make, color, year):
self.make = make
self.color = color
self.year = year
self.money = 4000
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make.title() + ' ' + self.color.title()
return long_name
def get_money(self):
print ("It costs money to buy this car " + str(self.money) )
def increment_money(self,coppen):
self.money += coppen
my_name_car = Car(' Perkins','red',2019)
print(my_name_car.get_descriptive_name())
my_name_car.get_money()
my_name_car.increment_money(100)
my_name_car.get_money()
[root@swt ~]# python3 simple.py
2019 Perkins Red
It costs money to buy this car 4000
It costs money to buy this car 4100
1.3 继承
\一个类继承 另一个类时,它将自动获得另一个类的所有属性和方法;原有的
类称为父类 ,而新类称为子类 。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。
1.3.1 子类的方法__init__()
[root@swt ~]# cat simple.py
class Car():
def __init__(self,make,color,year):
self.make = make
self.color = color
self.year = year
self.money = 0
def get_info(self):
info = str(self.year) + ' ' + self.make.title() + ' ' + self.color.title()
return info
class EverCar(Car):
def __init__(self,make,color,year):
super().__init__(make,color,year)
my_new_car=Car('ad','rad',2019)
print (my_new_car.get_info())
my_teala=EverCar('bc','yellow',2019)
print(my_teala.get_info())
[root@swt ~]# python3 simple.py
2019 Ad Rad
2019 Bc Yellow
1.3.2 给子类定义属性和方法
[root@swt ~]# cat simple.py
...
class EverCar(Car):
def __init__(self,make,color,year):
super().__init__(make,color,year)
self.size = 20
def describe_battery(self):
print("This car has a " + str(self.size) + "!")
my_new_car=Car('ad','rad',2019)
print (my_new_car.get_info())
my_teala=EverCar('bc','yellow',2019)
print(my_teala.get_info())
my_teala.describe_battery()
[root@swt ~]# python3 simple.py
2019 Ad Rad
2019 Bc Yellow
This car has a 20!
1.3.3 重写父类的方法
[root@swt ~]# cat simple.py
class Car():
def __init__(self,make,color,year):
self.make = make
self.color = color
self.year = year
self.money = 0
def get_info(self):
info = str(self.year) + ' ' + self.make.title() + ' ' + self.color.title()
return info
def fill_gas_tank():
print("This is need a gas tank!")
class EverCar(Car):
def __init__(self,make,color,year):
super().__init__(make,color,year)
self.size = 20
def describe_battery(self):
print("This car has a " + str(self.size) + "!")
def fill_gas_tank(self):
print("This is doesn't need a gas tank!")
my_new_car=Car('ad','rad',2019)
print (my_new_car.get_info())
my_teala=EverCar('bc','yellow',2019)
print(my_teala.get_info())
my_teala.describe_battery()
my_teala.fill_gas_tank()
[root@swt ~]# python3 simple.py
2019 Ad Rad
2019 Bc Yellow
This car has a 20!
This is doesn't need a gas tank!
\\如果有人对EverCar调用方法fill_gas_tank() ,Python将忽略Car 类中的方法fill_gas_tank() ,转而运行上述代码
1.3.4 将实例用作属性
[root@swt ~]# cat simple.py
class Name ():
def __init__(self,name,age,xingb):
self.name=name
self.age=age
self.xingb=xingb
self.taste=Taste()
def mension(self):
print ("\n" + self.name + " is a " + str(self.age) + " " + self.xingb)
class Taste():
def __init__(self,Install='basketball'):
self.Install=Install
def My_taste(self):
print("My interest is " + self.Install)
class Myname (Name):
def __init__(self,name,age,xingb):
super().__init__(name,age,xingb)
self.taste=Taste()
name_mension=Name('songwentian',20,'girl')
name_mension.mension()
name_mension.taste.My_taste()
Myname_mension=Myname('xiefei',22,'boy')
Myname_mension.mension()
Myname_mension.taste.My_taste()
[root@swt ~]# python3 simple.py
songwentian is a 20 girl
My interest is basketball
xiefei is a 22 boy
My interest is basketball
\\练一练
[root@swt ~]# cat simple.py
class Restaurant():
def __init__(self,name,taste,price):
self.name=name
self.taste=taste
self.price=price
self.flavors=Flavors(['water','cream','ice'])
def info(self):
restaurant_info="\n" + self.name + ' ' + self.taste + ' ' + str(self.price)
return restaurant_info
def simple(self):
print("This " + self.name + " is delicious")
class Flavors():
def __init__(self,component=['water','sugar','cream','ice']):
self.components=component
def explain(self):
print("The ingredients of this ice cream are:" )
for self.component in self.components:
print("----" + self.component)
class IceCream(Restaurant):
def __init__(self,name,taste,price):
super().__init__(name,taste,price)
self.flavors=Flavors()
IceCreamStand=Restaurant("Pudding","sweet",5)
print(IceCreamStand.info())
IceCreamStand.simple()
IceCreamStand.flavors.explain()
NewIcecream=IceCream("Mengniu","acid",10)
print(NewIcecream.info())
NewIcecream.simple()
NewIcecream.flavors.explain()
[root@swt ~]# python3 simple.py
Pudding sweet 5
This Pudding is delicious
The ingredients of this ice cream are:
----water
----cream
----ice
Mengniu acid 10
This Mengniu is delicious
The ingredients of this ice cream are:
----water
----sugar
----cream
----ice
\\
[root@swt ~]# cat simple.py
class User():
def __init__(self,name,uid,gid):
self.name=name
self.uid=uid
self.gid=gid
def info(self):
User_info="\n" + self.name.title() + ' uid is ' + str(self.uid) + ' and gid is ' + str(self.gid)
return User_info
def mension(self):
if self.uid <= 100:
print("This user is a system user!")
else:
pass
print("This user is a ordinary user!")
class Power():
def __init__(self,authoritys=['increase','delete','see','modify']):
self.authoritys=authoritys
def explain(self):
print("This user has permission:")
for self.authority in self.authoritys:
print("---" + self.authority)
class Systemuser(User):
def __init__(self,name,uid,gid):
super().__init__(name,uid,gid)
self.power=Power()
Myname=Systemuser('songwentian',30,30)
print(Myname.info())
Myname.mension()
Myname.power.explain()
Adminname=User('xiefei',120,30)
print(Adminname.info())
Adminname.mension()
[root@swt ~]# python3 simple.py
Songwentian uid is 30 and gid is 30
This user is a system user!
This user has permission:
---increase
---delete
---see
---modify
Xiefei uid is 120 and gid is 30
This user is a ordinary user!
1.4 导入类
1.4.1 导入单个类
[root@swt ~]# cat date.py
class User():
def __init__(self,username,useruid,usergid):
# 初始化用户的属性
self.username=username
self.useruid=useruid
self.usergid=usergid
def get_userinfo(self):
# 描述用户的信息
userinfo="\n" + self.username.title() + ' UID is ' + str(self.useruid) + ' and GID is ' + str(self.usergid)
return userinfo
def get_connpet(self,authoritys=['increase','delete','see','modify']):
# 打印用户的功能
self.authoritys=authoritys
print("The user's privileges are :")
for authority in self.authoritys:
print ("-" + authority)
def get_include(self):
# 打印用户是系统用户还是普通用户
if self.useruid <= 100:
print(self.username + " is a system user!")
else:
pass
print( self.username + " is a ordinary user!")
[root@swt ~]# cat date.py
from date import User
systemname=User('songwentian',10,20)
print(systemname.get_userinfo())
systemname.get_connpet()
systemname.get_include()
ordinaryname=User('xiefei',130,120)
print(ordinaryname.get_userinfo())
ordinaryname.get_connpet(['see','modify'])
ordinaryname.get_include()
[root@swt ~]# python3 date.py
Songwentian UID is 10 and GID is 20
The user's privileges are :
-increase
-delete
-see
-modify
songwentian is a system user!
Xiefei UID is 130 and GID is 120
The user's privileges are :
-see
-modify
xiefei is a ordinary user!
1.4.2 在一个模块中存储多个类
[root@swt ~]# cat car.py
class Car():
def __init__(self,model,color,price):
self.model=model
self.color=color
self.price=price
def info(self):
car_info="\nThis is price " + str(self.price) + "wan, his color " + self.color.title() + " to " + self.model.title() + "."
return car_info
def velocity(self,speed=100):
self.speed=speed
print(self.model.title() + " is speen " + str(self.speed) + "km/s!")
def mold(self,type='gas tank'):
self.type=type
if self.type == 'gas tank':
print(self.model.title() + " is a gasoline car!")
else:
print(self.model.title() + " is a tram!")
class TramCar():
def __init__(self,hour=7):
self.hour=hour
def menssion(self):
car_menssion="\nThe car charge for " + str(self.hour) + " hours!"
return car_menssion
def car_time(self,time=12):
self.time=time
print("This car can last for " + str(self.time) + " hours")
class ElectricCar(Car):
def __init__(self,model,color,price):
super().__init__(model,color,price)
self.TramCar=TramCar()
[root@swt ~]# cat car_test.py
from car import ElectricCar
My_new_car=ElectricCar("emma","rad",10)
print(My_new_car.info())
My_new_car.velocity(70)
My_new_car.mold('tram')
print(My_new_car.TramCar.menssion())
My_new_car.TramCar.car_time(10)
[root@swt ~]# python3 car_test.py
This is price 10wan, his color Rad to Emma.
Emma is speen 70km/s!
Emma is a tram!
The car charge for 7 hours!
This car can last for 10 hours
1.4.3 从一个模块中导入多个类
[root@swt ~]# cat car_test.py
from car import ElectricCar,Car
My_newcar=Car("chevrolet",'white',40)
print(My_newcar.info())
My_car=ElectricCar("emma","rad",10)
print(My_car.info())
[root@swt ~]# python3 car_test.py
This is price 40wan, his color White to Chevrolet.
This is price 10wan, his color Rad to Emma.
1.4.4 导入整个模块
[root@swt ~]# cat car_test.py
import car
My_newcar=car.Car("chevrolet",'white',40)
print(My_newcar.info())
My_car=car.ElectricCar("emma","rad",10)
print(My_car.info())
[root@swt ~]# python3 car_test.py
This is price 40wan, his color White to Chevrolet.
This is price 10wan, his color Rad to Emma.
1.4.5 导入模块中的所有类
[root@swt ~]# cat car_test.py
from car import *
1.4.6 在一个模块中导入另一个模块
[root@swt ~]# cat swt.py
class User():
def __init__(self,name,sex):
self.name=name
self.sex=sex
self.age=0
def user_info(self):
info="\nhis name is ".title() + self.name.title() + ", his sex is " + self.sex + '.'
return info
def user_age(self):
self.age += 18
print("His age is " + str(self.age))
def friends(self,friend):
myfriend=['xiefei','feige','feiye']
self.friend=friend
if self.friend in myfriend:
print( self.friend.title() + ' is his friend!')
else:
print(self.friend.title() + " not is his friend!")
[root@swt ~]# cat swt_test.py
from swt import User
class Hobby():
def __init__(self,tastes=['dress','game','chat']):
self.tastes=tastes
def interest(self):
print("His hobbies is :")
for self.taste in self.tastes:
print("-" + self.taste.title())
class Myname(User):
def __init__(self,name,sex):
super().__init__(name,sex)
self.interest=Hobby()
[root@swt ~]# cat my_swt.py
from swt import User
from swt_test import Myname
Myname_swt=Myname('songwentian','gril')
print(Myname_swt.user_info())
Myname_swt.user_age()
Myname_swt.friends('xiefei')
from swt_test import Hobby
Myname_swt=Hobby(['game','chat'])
Myname_swt.interest()
[root@swt ~]# python3 my_swt.py
His Name Is Songwentian, his sex is gril.
His age is 18
Xiefei is his friend!
His hobbies is :
-Game
-Chat
1.5 Python标准库
\Python标准库 是一组模块,安装的Python都包含它.可以使用其他程序员编写好的模块了,可使用标准库中的任何函数和类,为此只需在程序开头包含一条简单的import 语句.
\\练一练
[root@swt ~]# cat simple.py
# 模块random 包含以各种方式生成随机数的函数
# randint() 返回一个位于指定范围内的整数
from random import randint
class Die():
def __init__(self,sides=6):
self.sides=sides
def roll_die(self):
number=1
while number <= 10:
num1=randint(1,6)
print("6面筛子:" + str(num1))
num2=randint(1,10)
print("10面筛子:" + str(num2))
print("-----------")
number +=1
My_die=Die()
My_die.roll_die()