@chenwei123
2018-02-07T07:08:48.000000Z
字数 4357
阅读 363
Python
message = input("Tell me something, and I will repeat it back to you:")print(message)#input(),接受一个参数,即向用户显示的说明描述#int()获取数值输入age = input("How old are you?") #返回的是一个字符串, 要想使用一个数值,需要用 int()print(age)age = int(age)print(age)
python2.7输入。raw_input()提示用户输入,输入解读为字符串
def describe_pet(animal_type, pet_name):"""显示宠物信息"""print("\nI have a " + animal_type + ".")print("My " + animal_type + "'s name is " + pet_name.title() + ".")describe_pet("dog", "willie")describe_pet("willie", "dog")
注意:函数调用中实参的顺序要与函数定义中形参的顺序保持一致
def describe_pet(animal_type, pet_name):"""显示宠物的信息"""print("\nI hava a "+ animal_type+".")print("My "+animal_type+"'s name is "+pet_name.title()+".")describe_pet(animal_type="dog", pet_name="willie")describe_pet(pet_name="willie", animal_type="dog")
关键字实参是传递给函数的名称-值对,在实参中将名称和值关联起来。关键字实参无需考虑函数调用中实参的顺序
def describe_pet(pet_name, animal_type="dog"):"""显示宠物的信息"""print("\nI have a "+animal_type+".")print("My "+animal_type+"'s name is "+pet_name.title()+".")describe_pet(pet_name="willie")describe_pet("willie")describe_pet(pet_name="willie", animal_type="cat")describe_pet(animal_type="cat", pet_name="willie")describe_pet("willie", "cat")
函数调用中,如果给形参提供了实参时,将使用指定的实参值;否则,将使用形参的默认值
def make_pizza(*toppings):"""打印顾客点的所有配料"""print(toppings)make_pizza("aa")make_pizza("aa", "bb", "cc")
形参
*toppings中的星号是让 Python 创建一个名为toppings 的空元组,并将所有收到的值封装到这个元组中。
def build_profile(first,last,**user_info):"""创建一个字典,其中包含我们知道的有关用户的一切"""profile={}profile["first_name"] = firstprofile["last_name"] = lastfor key, value in user_info.items():profile[key] = valueuser_profile = build_profile("albert", "einstein", location="princeton", field="physics")print(user_profile)
形参
**user_info中的两个星号让 Python 创建一个名为 user_info的空字典,并将收到的所有名称-值对都封装到这个字典中。
#pizza.pydef make_pizza(size, *toppings):"""概述要制作的比萨"""print("\nMaking a " + str(size)+"-inch pizza with the following toppings:")for topping in toppings:print("- "+topping)#pizza.py 同目录下创建making_pizza.pyimport pizzapizza.make_pizza(16, "aa")pizza.make_pizza(12, "aa", "cc", "dd")
通用语法:
module_name.function_name()
from pizza import make_pizzamake_pizza(16, "aa")make_pizza(12, "aa", "cc", "dd")
from pizza import make_pizza as mpmp(16, "aa")mp(12, "aa", "cc", "dd")
如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名。
import pizza as pp.make_pizza(16, "aa")p.make_pizza(12, "aa", "cc", "dd")
from pizza import *
class Dog():"""一次模拟小狗的简单尝试"""def __init__(self, name, age):"""初始化属性 name 和 age"""self.name = nameself.age = agedef sit(self):"""模拟小狗被命令时蹲下"""print(self.name.title() + " is now sitting.")def roll_over(self):"""模拟小狗被命令时打滚"""print(self.name.title() + " rolled over!")def update_dog(self, name):"""修改属性name值"""self.name = name
补充说明:Python2.7创建类时,需要在括号内包含单词 object 。类似如:
class Dog(object)
my_dog = Dog("willie", 6)
my_dog.name, my_dog.agemy_dog.sit(), my_dog.roll_over()my_dog.name = "Mary"my_dog.update_dog("mary")
class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_descriptive_name(self):long_name = str(self.year)+" "+self.make+" "+self.modelreturn long_name.title()def read_odometer(self, mileage):print("This car has " + str(self.odometer_reading) + " miles on it.")def update_odometer(self, mileage):if mileage >= self.odometer_reading:self.odometer_reading = mileageelse:print("You can't roll back on odometer!")def increment_odometer(self, miles):self.odometer_reading += milesdef run(self):print("汽车在跑")class Battery():"""将电瓶这部分独立出来作为一个类"""def __init__(self, battery_size=70):self.battery_size = battery_sizedef 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_size = 70 #子类添加新属性self.battery_sizeself.battery = Battery() #将实例Battery()用作ElectricCar的属性self.batterydef describe_battery(self):"""打印一条描述电瓶容量的消息, 子类添加新方法describe_battery"""print("This car has a " + str(self.battery_size) + "-kwh battery.")def run(self):"""重写父类方法run"""print("电动汽车在跑")my_tesla = ElectricCar("tesla", "models", 2016)print(my_tesla.get_descriptive_name())my_tesla.describe_battery()
创建子类时,父类与子类必须同处一个文件中,并且父类在子类前面。定义子类时,必须在括号里指明父类的名称。super(),将父类和子类关联起来。
注意: Python2.7继承语法如下
class Car(object):def __init__(self, make, model, year):--snip--class ElectricCar(Car):def __init__(self, make, model, year):super(ElectricCar, self).__init__(make, model, year)--snip--
super()需要两个实参:子类名和对象 self。父类在括号里指定object
三个引号表示文档注释