码迷,mamicode.com
首页 > 编程语言 > 详细

python笔记十五(面向对象及其特性)

时间:2017-12-28 23:27:48      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:name   obj   对象   属性   super   并且   post   info   派生   

一、面向对象:

class(类):一类拥有共同属性对象的抽象;定义了这些对象的属性和方法
object(对象):是一个类实例化后的实例,类必须经过实例化才可以在程序中调用;

由于之前学习过java,对类和对象已经有了一定的了解了,就不再详细介绍。

技术分享图片

 

二、特性

encapsulation(封装):将内部的内容封装起来了。例如数据的设置、访问和处理结果我们都可以通过调用实例的方法直接获取,而不需要知道内部的处理逻辑。
inheritance(继承):一个类可以派生出子类,父类中定义的属性和方法被子类自动继承
polymorphism(多态):一个基类派生出了不同的子类,且每个子类都继承了同样的方法名的同时又对父类的方法做了不同的实现,这就是一种事物表现出的
多种形态。一个接口多种实现。

 

继承

>>> class Animal(object):
...     def run(self):
...         print("animal is running")
...
>>> class Dog(Animal):
...     pass
...
>>> dog1 = Dog()
>>> dog1.run()
animal is running

多继承

class People(object):

    def __init__(self,name,age):
        self.name = name
        self.age = age
    def say(self):
        print("%s say helllo"%self.name)

class Relation:
    def make_friends(self,obj):
        print("%s is making friends with %s"%(self.name,obj.name))

class Man(People,Relation):#在多继承的时候,如果两个父类都有init,会先继承左边的,并且只继承一个构造函数
                            #python3广度优先,python2经典类按深度优先继承,新式类按广度优先继承

    def __init__(self,name,age,money):
        #People.__init__(self,name,age) #这里重写的构造函数
        super(Man,self).__init__(name,age)#这里重写的构造函数
        self.money = money
        print("%s is born with %s money"%(self.name,self.money))

    def say(self):
        People.say(self) #在重写方法的时候调用父类的方法
        print("hahahahahahahha ")
m1 = Man("nadech",22,10000)
m1.say()
m2 = Man("lsw",22,1)
m1.make_friends(m2)

输出结果<<<<

nadech is born with 10000 money
nadech say helllo
hahahahahahahha
lsw is born with 1 money
nadech is making friends with lsw


多态

# Author:nadech
# 多态就是一个接口多个调用,在父类的方法中实现一个接口,每个子类的对象调用时有不同的输出
class Animal(object):
    def __init__(self,name):
        self.name = name
    def talk(self):
        pass

    @staticmethod    #静态方法,我们会在接下来一节中仔细介绍
    def animal_talk(obj):
        obj.talk()

class Dog(Animal):
    def talk(self):
        print("wow wow")

class Cat(Animal):
    def talk(self):
        print("meow")
d = Dog("狗狗")
c = Cat("猫猫")
Animal.animal_talk(c)
Animal.animal_talk(d)

 

python笔记十五(面向对象及其特性)

标签:name   obj   对象   属性   super   并且   post   info   派生   

原文地址:https://www.cnblogs.com/nadech/p/8137903.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!