先通过两张图来了解下类


类的概念
1、面向对象最重要的概念就是类(class)和实例(instance)
2、类是抽象的模块,可以理解为一个基础,比如Student类,而实例是根据类创建出来的一个个具体的“对象”
3、每个对象都拥有相同的方法,但各自的数据可能不同
创建一个类
定义类:关键字class
1、class后面紧跟类名,即Student,类名通常是大写开头的单词
2、紧接着是(object),表示该类是从哪个类继承下来的,通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类
class Student(object):
pass
实例化一个类
创建实例:类名+()
实例可以理解为类的替身,类是不能直接被使用的,只能通过实例化之后,用实例名代替
bar = Student()
使用一个类
类有属性和方法,可以将属性理解为静态的数据,方法理解为动态的处理函数
比如车都有轮子,都能开,那么轮子就是属性,开就是方法
# -*- coding: utf-8 -*-
# __author__ = 'Carina'
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
bar = Student('zhangsan', '85') # 实例化类
bar.print_score()
网友评论