---
title: "Python OOP Basic"
author: "fairy_xzc"
date: "2013-04-23T14:08:20Z"
tags: []
categories: ["编程语言"]
slug: "python-oop-basic"
draft: false
lastmod: "2013-04-23T14:12:32Z"
id: 1852016
url: "https://agilestyle.iteye.com/blog/1852016"
---

**第一个简单的类**

```
class FirstClass:                   #Define a class object
    def setdata(self, value):       #Define class methods
        self.data = value           #self is the instance

    def display(self):
        print(self.data)            #self.data: per instance
```

测试结果：   
![](http://dl.iteye.com/upload/attachment/0083/5358/d4fbb95e-a5fd-36ca-bc8d-02954b66186d.png)  
 

 

**继承**

```
class FirstClass:                   #Define a class object
    def setdata(self, value):       #Define class methods
        self.data = value           #self is the instance

    def display(self):
        print(self.data)            #self.data: per instance



class SecondClass(FirstClass):      #Inherits setdata
    def display(self):              #Changes display
        print('Current value = "%s"' % self.data)
```

测试结果：  
![](http://dl.iteye.com/upload/attachment/0083/5362/2bcb6b0d-3d4d-334f-a8e8-6b8a00304cba.png)  
 

 

**运算符重载**

```
class FirstClass:                   #Define a class object
    def setdata(self, value):       #Define class methods
        self.data = value           #self is the instance

    def display(self):
        print(self.data)            #self.data: per instance



class SecondClass(FirstClass):      #Inherits setdata
    def display(self):              #Changes display
        print('Current value = "%s"' % self.data)



class ThirdClass(SecondClass):
    def __init__(self, value):                  #__init__方法，也称为构造函数方法，用于初始化对象的状态
        self.data = value

    def __add__(self, other):                   #运算符重载，"+"表达式会触发"__add__"方法
        return ThirdClass(self.data + other)

    #对于print，Python把要打印的对象传递给__str__中的self，该方法返回的字符串看做是对象的打印字符串
    def __str__(self):                          
        return '[ThirdClass: %s]' % self.data

    def mul(self, other):                       #in-place change: named
        self.data *= other
```

 测试结果：  
![](http://dl.iteye.com/upload/attachment/0083/5360/99c13feb-0b63-3d06-b8ca-9b99f4ffc785.png)  
 

 

**一个简单完整的类**  
![](http://dl.iteye.com/upload/attachment/0083/5366/2646891b-9577-374c-a25f-4b6640e218fe.png)  
 

 

**一个完整的例子(Encapsulation, Inheritance, Polymorphism)**

```
class Person:
    def __init__(self, name, job=None, pay=0):
        self.name = name
        self.job = job
        self.pay = pay

    def getLastName(self):
        return self.name.split()[-1]

    def giveRaise(self, percent):
        self.pay = int(self.pay * (1 + percent))

    def __str__(self):
        return '[Person: %s, %s]' % (self.name, self.pay)

class Manager(Person):
    def __init__(self, name, pay):                      #Redefine constructor
        Person.__init__(self, name, 'manager', pay)
    
    def giveRaise(self, percent, bonus=.10):            #Redefine at this level
        Person.giveRaise(self, percent + bonus)         #Call Person's version

    def __str__(self):
        return '[Manager: %s, %s]' % (self.name, self.pay)

if __name__ == '__main__':
    p1 = Person('Michael Jordan')
    p2 = Person('Kobe Bryant', job='developer', pay=100000)
    print(p1)
    print(p2)
    print(p1.getLastName(), p2.getLastName())
    p2.giveRaise(.10)                         
    print(p2)

    p3 = Manager("David Stern", 50000)
    p3.giveRaise(.10)
    print(p3.getLastName())
    print(p3)

    print('--All three--')
    for object in (p1, p2, p3):
        object.giveRaise(.10)
        print(object)
```

测试结果：  
![](http://dl.iteye.com/upload/attachment/0083/5364/22914643-c98c-33ea-92a1-944edf2b0da2.png)