例子1:
class Restaurant(object):
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name=restaurant_name
self.cuisine_type=cuisine_type
def print_restauran(self):
print ("Name:"+self.restaurant_name)
print ("Type:"+self.cuisine_type)
def print_open(self):
print ("This time is Open!")
myrestrant=Restaurant("ChengBei",'6')
myrestrant.print_restauran()
myrestrant.print_open()
zhangsanrestrant=Restaurant("ChengNan",'4')
zhangsanrestrant.print_restauran()
zhangsanrestrant.print_open()
lisirestrant=Restaurant('TianJing','3')
lisirestrant.print_restauran()
lisirestrant.print_open()
例子2:
class User(object):
def __init__(self,first_name,last_name):
self.first_name=first_name
self.last_name=last_name
def descibe_user(self):
print ("first_name:"+self.first_name)
print ("last_name:"+self.last_name)
def greet_user(self):
name=self.last_name;
if name =="san":
print ("Hello,admin!")
else:
print ("KO!")
d_user=User('zhang','san')
d_user.descibe_user()
d_user.greet_user()
注意python的缩进控制。
给属性指定默认值。
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odlometer=0
def get_descriptive_name(self):
long_name=str(self.year)+','+self.make+','+self.model
return long_name.title()
my_new_car=Car('audi','a4',2016)
print (my_new_car.get_descriptive_name())
修改默认值
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odlometer=0
def get_descriptive_name(self):
long_name=str(self.year)+','+self.make+','+self.model
return long_name.title()
my_new_car=Car('audi','a4',2016)
print (my_new_car.get_descriptive_name())
meter=my_new_car.odlometer=23
mymeter=str(meter)
print ("meter:"+mymeter)
子类的方法
子类的初始化
class Car(object):
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odlometer=0
class Electronic(Car):
def __init__(self,make,model,year):
super(Car,self).__init__(self,make,model,year)
my_elec_car=Electronic('Tesla','Model S',2019)
super()是一个特殊函数,帮助将Python父类和子类
给子类定义属性和方法
重写父类的方法
导入类
导入单个类
from car import Car
在一个模块中储存多个类
from car import Car,ElectriCar,GasCar
文件异常处理
python文件操作
例:
for line in open("ip.txt"):
print line
文本写入操作
使用try-execpt捕捉异常
try:
print ("Error!")
except ZeroDivisionError:
print ("You can't divide by zero!)
JSON (JavaScript Object Notation)
使用json.dump()和json.load()