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']

猜你喜欢

转载自blog.csdn.net/mouday/article/details/80474451
今日推荐