#!/usr/bin/python3
import _thread
import time
##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)
##print("My dog's name is " + my_dog.name )
##
### 为线程定义一个函数
##def print_time( threadName, delay):
## count = 0
## while count < 20:
## time.sleep(delay)
## count += 1
## print ("%s: %s\r\n" % ( threadName, time.ctime(time.time()) ))
##
### 创建两个线程
##try:
## _thread.start_new_thread( print_time, ("Thread-1", 2, ) )
## _thread.start_new_thread( print_time, ("Thread-2", 2, ) )
##except:
## print ("Error: 无法启动线程")
##
##while 1:
## pass
##2018年10月5日13:44:32
#2018年10月5日13:44:32
"""Python关于类(Class)的学习"""
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)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
"""调用方法"""
my_dog.sit()
my_dog.roll_over()
"""动手试一试"""
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
self.resname = restaurant_name
self.cuistype = cuisine_type
def describe_restaurant(self):
print(self.resname + " is the restaurant name.")
print(self.cuistype + " is the restaurant cuisine_type")
def open_restaurant(self):
print("The restaurant is open now")
myrestaurant = Restaurant("Spicy way","Chinese food")
myrestaurant.describe_restaurant()
myrestaurant.open_restaurant()
res1 = Restaurant("Zuoxiangyoulin","XiangCai")
res2 = Restaurant("Aiwanting","XiangCai")
res3 = Restaurant("Lanzhoufood","Lanzhou")
res1.describe_restaurant()
res2.describe_restaurant()
res3.describe_restaurant()
class User():
def __init__(self,first_name,last_name,age,grade,professional):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.grade = grade
self.professional = professional
def describe_user(self):
print(self.first_name + " is My First_name.")
print(self.last_name + " is My Last_nme.")
print("My age is " + self.age + ".")
print("My grade is " + self.grade + ".")
print(self.professional + " is my job.")
def great_user(self):
print("Welcome, "+ self.first_name + self.last_name + " nice to meet you!")
stu1 = User("Pan","Yan","22","Male","Engineer")
stu1.describe_user()
stu1.great_user()
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
##long_name = 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):
if miles >= 0:
self.odometer_reading += miles
else:
print("You can't set an miles with negative increments")
def fill_gas_tank(self,gallon):
print("The car have "+ str(gallon) + ' capacity')
##9.3.5 将实例用作属性
class Battery():
def __init__(self,battery_size=70):
self.battery_size = battery_size+10
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()
## def describe_battery(self):
## print("This car has a " + str(self.battery_size) + "-kWh battery.")
def fill_gas_tank(self,gallon):
print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.fill_gas_tank(20)
my_new_car = Car('andi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
my_new_car.updata_odometer(10)
my_new_car.read_odometer()
my_new_car.increment_odometer(100)
my_new_car.read_odometer()
创建和使用类
class Dog():
###class 关键字
###Dog()ClassName一般首字母大写
方法 __init__()
exp: __init__(self,name,age):
### __init__()称为方法,我们将方法__init__() 定义成了包含三个形参:self 、name 和age 。在这个方法的定义中,形参self 必不可少,还必须位于其他形参的前面。为何必须在方法定义中包含形参self 呢?因为Python调用这个__init__() 方法来创建Dog 实例时,将自动传入实参self 。每个与类相关联的方法调用都自动传递实参self ,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。我们创建Dog 实例时,Python将调用Dog 类的方法__init__() 。我们将通过实参向Dog() 传递名字和年龄;self 会自动传递,因此我们不需要传递它。每当我们根据Dog 类创建实例时,都只需给最后两个形参(name 和age )提供值。
self.name = name
self.age = age
###以self为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实例来访问这些变量。可通过实例访问到的变量称为属性。
my_dog = Dog('Hole',6)
my_dog.name###要访问实例的属性,可以使用句点表示法。
调用方法
my_dog.sit()
my_dog.roll_over()###实例名称+'.'+方法。
在class Car里面,我们给类中的每个属性制定初始值,
修改属性的值
1.直接修改属性的值。
2.通过方法修改属性的值
继承
class Car():
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
父类必须位于子类的前面,定义子类时,必须在括号内指定父类名称。
使用super()函数将父类和子类关联起来,
当子类有某个属性与父类不一致时,譬如小汽车和电动汽车,电动汽车没有油箱,我们可以通过重写父类的方法,给子类写一个和父类重名的方法。使子类的该属性值不冲父类处继承。
将实例用作属性
使用代码模拟实物时,属性和方法的文件都越来越长,可以将类的一部分作为一个独立的类提取出来。
网友评论