天天看點

Python程式設計:python面向對象代碼示例

類似的文章:

  1. Python程式設計:class類面向對象
  2. Python程式設計:面向對象深入

文章内容

面向對象 類, 對象
屬性和方法
封裝 資料隐藏 
繼承(object) 代碼複用 
多态 接口重用
magic method魔術方法
構造對象
運算符
類的展現
類的屬性通路      

面向對象 類, 對象

構造函數 def __init__
析構函數 def __del__

新式類(object)和老式類      

屬性通路控制 靠自覺

public   name
protected  _age 
private __weight      

函數和方法(類)

public 
protected
private

method
@classmethod
@property      

類繼承

調用父類方法
super(superclass, self).method(args)
superClass.method(args)

isinstance
issubclass
多繼承      

多态:繼承 方法重寫

magic method魔術方法

對象執行個體化:建立對象 -》初始化對象
__new__(cls)
__init__(self)
回收對象
__del__(self)

運算符
__cmp__(self, other)
__eq__(self, other)
__lt__(self, other)
__gt__(self, other)
__add__(self, other)
__sub__(self, other)
__mul__(self, other)
__div__(self, other)
__or__(self, other)
__and__(self, other)

轉為字元串
__str__ -> 适合人看
__repr__ -> 适合機器看 -> eval()直接運作
__unicode__
__dir__

設定對象屬性
def __setattr__(self, name, value)
    self.__dict__[name] =value

錯誤設定,預設遞歸1000次
def __setattr__(self, name, value):
    setattr(self, name, value)

查詢對象屬性
__getattr__(self, name)  沒有被查詢到調用
__getattribute__(self, name)  每次查詢都會調用

删除對象屬性
__delattr__(self, name)      

代碼示例

類的繼承

# -*- coding: utf-8 -*-
# 父類
class Person(object):
    count = 0

    # 建立對象
    def __new__(cls, *args, **kwargs):
        print("call __new__")
        return super(Person, cls).__new__(cls, *args, **kwargs)

    # 初始化
    def __init__(self, name, age, weight):
        print("call __init__")
        self.name = name
        self._age = age
        self.__weight = weight
        Person.count += 1

    @classmethod
    def get_count(cls):
        return cls.count

    @property
    def weight(self):
        return self.__weight

    def say_hello(self):
        print("hello")

# 子類
class EarthPerson(Person):
    def __init__(self, name, age, weight, language):
        super(EarthPerson, self).__init__(name, age, weight)
        self.language = language

    # 重寫父類方法
    def say_hello(self):
        print("hello, my name is %s"%self.name)


def introduce(person):
    if isinstance(person, Person):
        person.say_hello()

if __name__ == '__main__':

    p1 = Person("tom", 23, 60)
    """
    call __new__
    call __init__
    """

    p2 = EarthPerson("jack", 24, 65, "English")
    """
    call __new__
    call __init__
    """

    print(p1)  # <__main__.Person object at 0x106fb2350>

    print(p1.__dict__)
    # {'_age': 23, 'name': 'tom', '_Person__weight': 60}

    print(dir(p1))
    """
    ['_Person__weight', '__class__', '__delattr__', '__dict__', 
    '__doc__', '__format__', '__getattribute__', '__hash__', 
    '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', 
    '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
    '__weakref__', '_age', 'count', 'get_count', 'name', 'say_hello', 'weight']
    """

    print(p1.name)  # tom
    print(p1._age)  # 23
    print(p1._Person__weight)  # 60
    print(p1.weight)  # 60
    print(Person.count)  # 2
    print(Person.get_count())  # 2
    p1.say_hello()  # hello


    print(p2)  #  <__main__.EarthPerson object at 0x106fb2390>
    print(issubclass(EarthPerson, Person))  # True
    print(isinstance(p2, Person))  # True
    p2.say_hello()  # hello, my name is jack
    introduce(p2)  # hello, my name is jack
    introduce(p1)  # hello      

魔術方法

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        if isinstance(other, Point):
            if self.x == other.x and self.y == other.y:
                return True
            else:
                return False
        else:
            raise Exception("the type must be Ponit")

    def __add__(self, other):
        if isinstance(other, Point):
            x = self.x + other.x
            y = self.y + other.y
            return Point(x, y)
        else:
            raise Exception("the type must be Ponit")

    def __str__(self):
        return "Ponit(x={x}, y={y})".format(x=self.x, y=self.y)

    def __dir__(self):
        return self.__dict__.keys()

    def __getattribute__(self, name):
        # return getattr(self, name) 錯誤
        # return self.__dict__[name] 錯誤
        return super(Point, self).__getattribute__(name)

    def __setattr__(self, name, value):
        # setattr(self, name, value) 錯誤
        self.__dict__[name] = value


if __name__ == '__main__':

    point1 = Point(1, 2)
    point2 = Point(1, 2)
    print(point1 == point2)  # True
    print(point1 + point2)  # Ponit(x=2, y=4)
    print(dir(point1))  # ['x', 'y']