python学习笔记(五)---函数与类

函数

def为定义函数的一个标志

demo1:

def greet_user(username):
    print("Hello, " + username.title() + "!")

greet_user('jesse')
> Hello Jesse!

形参与实参

形参即定义函数时函数括号里面的参数,实参即实际使用过程中传进去的参数

位置实参与关键字实参

demo:

def describe_pet(animal_type, pet_name):
	"""显示宠物的信息"""
	print("
I have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")


describe_pet('hamster', 'harry')
"""以上在调用函数的过程中就使用了位置实参"""

防止形参顺序记混,可以采用关键字实参

def describe_pet(animal_type, pet_name):
	"""显示宠物的信息"""
	print("
I have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")


describe_pet(naimal_type ='hamster', pet_name= 'harry')
"""引用了形参中的关键字"""

默认值

编写函数时,可给每个形参指定的默认值.

demo:

def describe_pet (pet_name, animal_type= 'dog'):
	"""显示宠物的信息"""
	print('
 i have a ' + animal_type + '.')
	print('my' + animal_type + "'s name is " + pet_name.title() + '.')
describe('willie')
> I have a dog.
> My dog's name is Willie.

传递任意数量的实参
demo1:

def make_pizza(*toppings):
	print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
>
('pepperoni')
('mushrooms', 'green peppers', 'extra cheese')
"""
形参名*toppings中的星号让python创建一个名为toppings的空元组,并将收到的实参填充进去
"""

demo2:

def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("
Making a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
>
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

使用任意数量的关键字实参

def build_profile(first, last, **user_info):
	"""创建一个字典,其中包含我们知道的有关用户的一切"""
	profile = {}
	profile['first_name'] = first
	profile['last_name'] = last 
		for key, value in user_info.items():
	profile[key] = value
	return profile
user_profile = build_profile('albert', 'einstein',location='princeton',field='physics')
print(user_profile)
>
{'first_name': 'albert', 'last_name': 'einstein','location': 'princeton', 'field': 'physics'}
导入模块中的所有函数
from pizza import*

import 语句中的星号让Python将模块pizza 中的每个函数都复制到这个程序文件中。由于导入了每个函数,可通过名称来调用每个函数,而无需使用句点表示法

方法__init__()

demo:

  1. 创建了一个dog类
class Dog: 
	"""一次模拟小狗的简单尝试"""
	def __init__(self, name, age):
		"""初始化属性name和age"""
		self.name = name
		self.age = age
	def sit(self):
		"""模拟小狗被命令时蹲下"""
		print(self.name.title() + " is now sitting.")
	def roll_over(self):
		"""模拟小狗被命令时打滚"""
		print(self.name.title() + " rolled over!")

ps:1.用class定义一个新的类.
2. 调用这个Dog类 2.类的命名必须用驼峰命名法

my_dog = Dog('bob', '6')
my_dog.sit()
my_dog.roll_over()
>
Bob is now sitting.
Bob rolled over!
  1. 修改属性的值
print(my_dog.age)
my_dog.age = 7
print(my_dog.age)
>6
>7
  1. 继承

编写类时,并非总是要从空白开始。如果你要编写的类是另一个现成类的特殊版本,可使用继承 。一个类继承 另一个类时,它将自动获得另一个类的所有属性和方法;原有的
类称为父类 ,而新类称为子类 。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。

demo:
先创建一个Animals类

class Animals:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def run(self):
        print(self.name + ' is able to run')

    def jump(self):
        print(self.name + ' can jump')

再创建一个Dog类

class Dog(Animals):
    def eat(self):
        print(self.name + ' eat meet')

调用这个dog类

my_dog = Dog('bob', 6)
my_dog.eat()
my_dog.jump()
my_dog.run()
>
bob eat meet
bob can jump
bob is able to run
关于赋予子类新的属性

demo:

class Dog(Animals):
    def __init__(self, name, age, color):
        self.name = name
        self.age = age
        self.color = color

可以这样采用一种重定义的方法,继承时候取其精华,去其糟泊.但必须保留其父类原来的定义

对于类的导入

demo

from car import Car  导入一个类
from car import Car,Animal   导入多个类
from car import *   导入所有的类
原文地址:https://www.cnblogs.com/l0nmar/p/12553865.html