八、python面向对象编程

1 面向对象编程和面向过程编程区别?

  在至今我们编写的所有程序中,我们曾围绕函数设计我们的程序,也就是那些能够处理数据的代码块。这被称作面向过程( Procedure-oriented) 的编程方式。还有另外一种组织起你的程序的方式,它将数据与功能进行组合,并将其包装在被称作对象的东西内。在大多数情况下,你可以使用过程式编程,但是当你需要编写一个大型程序或面对某一更适合此方法的问题时,你可以考虑使用面向对象式的编程技术。 

2 self(和java中的this关键字一样,代表本类的一个引用)

  self存在类方法中,类方法与普通函数只有一种特定的区别——前者必须有一个额外的名字,这个名字必须添加

到参数列表的开头(即self),但是你不用在你调用这个功能时为这个参数赋值,Python 会为它提供。

3 最简单的类

class Person:
    pass # 一个空的代码块
p = Person()
print(p)
#结果
I:\Python34\python.exe F:/python/demo/test.py
<__main__.Person object at 0x00000000023EA080>

 注意:本例中打印出了对象在内存中的地址。如上例子出现的地址可能与在你电脑上所看到的地址不同,因为python会在他找到的任何空间来存储对象。

4 类变量和对象变量的区别

class Robot:
    population = 0                                                 #该变量为类变量
    def __init__(self, name):
        """初始化数据"""
        self.name = name                                           #self由对象分配,是一个对象变量。
        print("(Initializing {})".format(self.name))
        # 当有人被创建时,机器人将会增加人口数量
        Robot.population += 1
    def die(self):
        """我挂了。"""
        print("{} is being destroyed!".format(self.name))
        Robot.population -= 1
        if Robot.population == 0:
            print("{} was the last one.".format(self.name))
        else:
            print("There are still {:d} robots working.".format( Robot.population))
    def say_hi(self):
        """来自机器人的诚挚问候
        没问题,你做得到。"""
        print("Greetings, my masters call me {}.".format(self.name))
    @classmethod                                                  #这是一个类方法,类方法传递的一个参数可以直接调用类变量。
    def how_many(cls):
        """打印出当前的人口数量"""
        print("We have {:d} robots.".format(cls.population))
droid1 = Robot("R2-D2")
droid1.say_hi()
Robot.how_many()
#结果:
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.

说明:在本例中, population Robot 类,因此它是一个类变量。 name 变量属于一个对象( 通过使用 self 分配) ,因此它是一个对象变量 

posted @ 2017-09-18 16:39  国境之南时代  阅读(135)  评论(0编辑  收藏  举报