python學習第三天

例子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()
相關文章
相關標籤/搜索