每天5分钟轻松学python!

类是基础和核心的内容,难是不难,倒是很多细节需要注意!python类没有圆括号和花括号,只有冒号。这一点上和方法类似。

每天5分钟轻松学python!

#!/usr/bin/env python

# -*- coding:utf-8 -*-

#

#无论java还是python,类的内容都非常重要!

# Are you interested in the class? Please follow me and study!

#基础复盘

扫描二维码关注公众号,回复: 4885548 查看本文章

#面向对象的编程是最有效的编程方式之一。

# 程序员将现实世界的情景和事物具有的普遍的特点编写成类。

# 然后将类实例化,即创建对象,该对象就会自动具备类的特性。

#创建和使用类

#格式 class 类名 冒号

#注意这里没有java类似的花括号

#方法 __init__(),self形参必须有,位于最前面。

class Human():

'''简单概述人类的特性'''

def __init__(self,name,singing):

'''初始化属性'''

self.name = name

self.singing = singing

def sing(self):

print(self.name.title()+' is singing rap.')

每天5分钟轻松学python!

#根据类创建实例

#实例名 = 类名(形参1,形参2,...)

jesse = Human('Jesse','rap')

#调用方法

#句点表示法:实例名 英文输入法下的点 方法

jesse.sing()

#访问属性

#实例名 英文输入法下的点 属性名

jesse.singing

#创建多个实例

class Flower():

def __init__(self,name,color):

self.name = name

self.color = color

def print_flower(self):

print(self.name.title()+' is '+self.color+'.')

rose = Flower('rose','white')

rose.print_flower()

orchid = Flower('orchid','blue')

orchid.print_flower()

进群:960410445 即可获取数十套PDF!

每天5分钟轻松学python!

#上期参考答案(汽车)

def make_car(manufacturer,model,**car_info):

'''汽车的生产商和型号,以及颜色'''

car = {}

car['manufacturer'] = manufacturer

car['model'] = model

for key,value in car_info.items():

car[key] = value

return car

car = make_car('subaru', 'outback', color='blue', tow_package=True)

print(car)

猜你喜欢

转载自blog.csdn.net/qq_42156420/article/details/86349361