函数是带名字的代码块,用于完成具体的工作,使用关键词def来定义。
def greet_user():
print("Hello!")
greet_user() #调用定义的函数
def language(name,language): #形参
print(f"{name} is good at {language}")
language('Bob','Python') #实参
language('Alice','C')
def pet(name,type='dog'): #'type'为默认值
print(f"Its name is {name}\nIts type is {type}")
pet('Dabai')
def format_name(first_name,last_name):
name=f"{first_name.title()} {last_name.title()}"
return name
name=format_name('li','wasai')
print(name)
def make_pizza(size,*toppings):
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(16,'mushrooms','green peppers','extra cheese')
def build_profile(first,last,**user_info):
user_info['first_name']=first
user_info['last_name']=last
return user_info
user_profile=build_profile('Li','Wasai',
location='Jining',field='computer')
print(user_profile)
from numpy import array,arange
print(array([1,2,3,4,5]))
import numpy as np
print(np.array([1,2,3,4,5]))
from numpy as *
print(array([1,2,3,4,5]))
面向对象编程
根据类来创建对象称为实例化
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
self.steps = 0 给属性制定默认值,无需再用形参来定义
def sit(self):
print(f"{self.name} is now sitting")
def roll_over(self):
print(f"{self.name} rolled over")
def run(self):
print(f"{self.name} have run {self.steps} steps")
def update_run(self,steps): #通过方法修改属性的值
self.steps=steps
#使用类和实例
my_dog = Dog('Dabai', 6)
print(f"its name is {my_dog.name}\nits age is {my_dog.age}")
my_dog.sit() #调用方法
my_dog.roll_over()
my_dog.run()
my_dog.update_run(10000)
my_dog.run()
方法__init__()是类必不可少的,每当你根据Dog类创建新实例时,Python都会自动运行它。在这个方法的名称中,开头和末尾各有两个下划线,这是一种约定。
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=f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
print(f"This car has {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 on adometer!")
def increment_odometer(self,miles):
self.odometer_reading+=miles
class Car:
--snip--
class ElectricCar(Car): #定义子类时,必须在圆括号内指定父类的办法
def __init__(self,make,model,year):
super().__init__(make,model,year) #super()让你能够调用父类的办法
self.battery_size=75 #让子类定义属性
def describe_battery(self): #让子类定义方法
print(f"This car has a {self.battery_size}-kwh battery")
def fill_gas_tank(self): #重写父类的方法
print("This car doesn't need a gas tank!")
my_tesla=ElectricCar('tesla','model s',2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
3.将实例用作属性
class Car:
--snip--
class Battery: #定义一个新类,表示电动汽车电瓶的属性和方法
def __init__(self,battery_size=75):
self.battery_size
def describe_battery(self):
print(f"This car has a {self.battery_size}-kwh battery")
class ElectricCar(Car): #定义子类时,必须在圆括号内指定父类的办法
def __init__(self,make,model,year):
super().__init__(make,model,year) #super()让你能够调用父类的办法
self.battery=Battery() #创建Battery实例赋给属性self.battery
def fill_gas_tank(self): #重写父类的方法
print("This car doesn't need a gas tank!")
my_tesla=ElectricCar('tesla','model s',2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()