类
1、创建和使用类
1.1 创建Do类
```
class Dog(): #类的首字母大写
'''一次模拟小狗的简单尝试'''
def _init_(self,name,age): #_init_()是一个特殊的方法,一种约定。形参self必不可少
'''初始化属性name和age'''
self.name=name #以self为前缀的变量都可供类中的所有方法使用,称为属性
self.age=age
def sit(self):
'''模拟小狗被命令时蹲下'''
print(self.name.title()+" is now sitting.")
def roll_over(self):
'''模拟小狗被命令时打滚'''
print(self.name.title()+" rolled over!")
```
1.2 根据类创建实例
```
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()
```
-->
```My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.
Willie rolled over!```
1.3 修改属性的值
```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.")
my_new_car=Car('audi','a4',2016)
my_new_car.odometer_reading=23 #直接修改属性的值
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer() #调用函数中的方法
```
结果:
2016 Audi A4
This car has 23 miles on it.
1.4 通过方法修改属性的值
```
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 update_odometer(self,mileage): #添加一个函数并传递参数来修改属性odometer的值
self.odometer_reading=mileage
my_new_car=Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(46) #通过调用函数重新赋值
my_new_car.read_odometer()
```
结果:
```
2016 Audi A4
This car has 46 miles on it.
```
1.5 通过方法对属性的值进行新增
```
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=51
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 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_new_car=Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23500)
my_new_car.read_odometer()
my_new_car.increment_odometer(1000)
my_new_car.read_odometer()
```
结果:
```
2016 Audi A4
This car has 23500 miles on it.
This car has 24500 miles on it.
```
python练习
#九九乘法表
```
for i in range(1,10):
for j in range(1,i+1):
print(i*j,end=" ")
print("\n")
```
结果:
```
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
```