面向对象,即是将具备某种共性的事物抽象成一个类(模板),然后再根据类来创建实例对象进行具体的使用。

概述

  • 面向过程:根据业务逻辑从上到下写垒代码
  • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
  • 面向对象:对函数进行分类和封装,让开发“更快更好更强...”
本节学习目标:
  • 创建类和对象
  • 面向对象三大特性:封装、继承、多态
  • 类成员:变量(类变量,实例变量)、方法(普通方法,类方法,静态方法)、属性)
  • 类和对象在内存中的保存情况
  • 类成员修饰符:公有成员xx,私有成员__xx
  • 类的特殊成员:__doc__,__module__,__class__,__init__,__call__,__dict__,__str__

创建类和对象


class Car(object): # 创建类
    can_run=True # 类变量

    def __init__(self,name): # 构造函数
        self.name=name # 实例变量

    def run(self):
        return '%s run...' %self.name

bmw=Car("BMW")     # 通过类创建实例对象
print bmw.can_run  # 通过实例对象调用类变量
print bmw.run()   # 通过实例变量调用方法



运行结果:



True
BMW run...



面向对象的三大特性:封装、继承、多态



class Person(object):
    sex = 'M'

    def __init__(self, name):
        self.name = name

    def speak(self):
        return 'Human can speak...'


class Student(Person):
    ''' Student继承于Person'''
    id = 0 # 类变量,公有
    __score=60 # 类变量,私有

    def __init__(self, name, grade):
        super(Student, self).__init__(name)
        self.grade = grade  # 实例变量
        Student.id += 1     # 每创建实例一次,类变量+1
        self.id = Student.id  # 实例变量

    def job(self):
        return '%s is leaning in grade %s' % (self.name, self.grade)


class Teacher(Person):
    def __init__(self, name, course):
        super(Teacher, self).__init__(name)
        self.course = course  # 课程

    def job(self):
        return '%s is teaching %s' % (self.name, self.course)

    def speak(self):
        ''' 重写父类speak 方法'''
        return '%s can speak %s' % (self.name, self.course)


# 根据Student类创建实例对象s1
s1 = Student('Milton', 1)
print 's1.name:', s1.name  # 调用实例s1变量name
print 's1.id:', s1.id
print 's1.job:', s1.job()  # 通过实例s1调用类方法
# 继承父类的方法与属性
print 's1.speak:', s1.speak()
print 's1.sex:', s1.sex

# 重写父类的方法
t1 = Teacher('Loveyp', 'English')
print 't1.speak:', t1.speak()
# 多态
for p in [Student('Perter', 1), Teacher('Marry', 'English')]:
    print p.job()



运行结果:



通过实例对象调用实例变量,类方法,类变量:
s1.name: Milton
s1.id: 1
s1.count: 1
s1.job: Milton is leaning in grade 1
**************************************************
子类s1中继承父类的方法与属性:
s1.speak: Human can speak...
s1.sex: M
**************************************************
子类重写父类的方法:
t1.speak: Loveyp can speak English
******************************
多态:
Perter is leaning in grade 1
Marry is teaching English



类成员:变量(类变量,实例变量)、方法(普通方法,类方法,静态方法)、属性



class Car(object):
    count = 0  # 类变量
    style = "SUV"
    tax = 0.8

    def __init__(self, name, money):
        self.name = name  # 实例变量
        self.money = money
        Car.count += 1  # 调用类变量

    # 普通方法
    def run(self):
        return '%s run...' % self.name

    @classmethod  # 类方法,类方法中不能使用实例变量
    def play_music(cls, song):
        return '%s car can playing music %s' % (cls.style, song)

    @staticmethod  # 静态方法,不能直接使用类变量与实例变量
    def add_gas(name):
        return '%s can add_gas...' % name

    @property # 将方法设置为属性
    def price(self):
        return self.money * Car.tax

    @price.setter
    def price(self, money):
        self.money = money


bmw = Car("BMW", 80)
print "实例对象调用类变量:", bmw.count
print "类直接调用类变量:", Car.count
print "实例对象调用方法:", bmw.run()
print "实例对象调用实例变量:", bmw.name

try:
    Car.run()
except Exception, e:
    print "类直接调用方法失败:", e
aodi = Car("AODI", 100)
print "实例对象调用类变量:", aodi.count
print "类直接调用类变量:", Car.count

print "实例对象调用类方法:", aodi.play_music("Hello World")
print "类直接调用类方法:", Car.play_music("ABC")

try:
    aodi.add_gas()
except Exception, e:
    print "静态方法直接引用实例变量:", e
print "静态方法中传入参数:", aodi.add_gas(aodi.name)

print "修改属性前访问属性:",aodi.price
aodi.price = 200
print "修改属性后访问属性:",aodi.price



运行结果:



实例对象调用类变量: 1
类直接调用类变量: 1
实例对象调用方法: BMW run...
实例对象调用实例变量: BMW
类直接调用方法失败: unbound method run() must be called with Car instance as first argument (got nothing instead)
实例对象调用类变量: 2
类直接调用类变量: 2
实例对象调用类方法: SUV car can playing music Hello World
类直接调用类方法: SUV car can playing music ABC
静态方法直接引用实例变量: add_gas() takes exactly 1 argument (0 given)
静态方法中传入参数: AODI can add_gas...
修改属性前访问属性: 64.0
修改属性后访问属性: 160.0



类和对象在内存中的保存情况



class Car(object):
    count = 0  # 类变量
    style = "SUV"

    def __init__(self, name):
        self.name = name  # 实例变量
        Car.count += 1  # 调用类变量

    # 普通方法
    def run(self):
        return '%s run...' % self.name

    @classmethod  # 类方法,类方法中不能使用实例变量
    def play_music(cls, song):
        return '%s car can playing music %s' % (cls.style, song)

    @staticmethod  # 静态方法,不能直接使用类变量与实例变量
    def add_gas(name):
        return '%s can add_gas...' % name


bmw = Car("BMW")
bmw.color="white"
aodi = Car("AODI")


 

python面向对象文件引用导入 python 面向对象 类_类方法

类成员修饰符:公有成员xx,私有成员__xx



class Car(object):
    __count = 0  # 类变量,私有
    style="SUV"  # 类变量,公有

    def __init__(self, name):
        self.name = name  # 实例变量
        Car.__count += 1  # 调用类变量

bmw = Car("BMW")
try:
    print bmw.__count
except Exception,e:
    print "外部调用类私有变量:",e
print "外部调用类公有变量:",bmw.style



运行结果:



外部调用类私有变量: 'Car' object has no attribute '__count'
外部调用类公有变量: SUV



类的特殊成员:__doc__,__module__,__class__,__init__,__call__,__dict__,__str__



class Car(object):
    '''小车模型'''
    style = "SUV"  # 类变量,公有

    def __init__(self, name):
        self.name = name  # 实例变量
        print '__init__ function call...'

    def __call__(self, *args, **kwargs):
        print '__call__ function call...'

    def __str__(self):
        return "this is a nice card!"


print "文档注释", Car.__doc__
print "模块名:", Car.__module__
print "类型:", Car.__class__
bmw = Car("BMW")
bmw()
print "类成员:", Car.__dict__
print "实例成员:", bmw.__dict__
print "str 输出:", bmw



运行结果:



文档注释 小车模型
模块名: __main__
类型: <type 'type'>
__init__ function call...
__call__ function call...
类成员: {'__dict__': <attribute '__dict__' of 'Car' objects>, '__module__': '__main__', '__call__': <function __call__ at 0x039098F0>, 
'__str__': <function __str__ at 0x03909870>, '__weakref__': <attribute '__weakref__' of 'Car' objects>, 'style': 'SUV', 
'__init__': <function __init__ at 0x039098B0>, '__doc__': '\xe5\xb0\x8f\xe8\xbd\xa6\xe6\xa8\xa1\xe5\x9e\x8b'}
实例成员: {'name': 'BMW'}
str 输出: this is a nice card!