Python编程:python面向对象

简介: Python编程:python面向对象

类似的文章:


Python编程:class类面向对象

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']
相关文章
|
3月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
292 102
|
3月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
315 104
|
3月前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
262 103
|
3月前
|
机器学习/深度学习 人工智能 数据挖掘
Python:现代编程的首选语言
Python:现代编程的首选语言
194 82
|
2月前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
180 3
|
2月前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
436 3
|
2月前
|
并行计算 安全 计算机视觉
Python多进程编程:用multiprocessing突破GIL限制
Python中GIL限制多线程性能,尤其在CPU密集型任务中。`multiprocessing`模块通过创建独立进程,绕过GIL,实现真正的并行计算。它支持进程池、队列、管道、共享内存和同步机制,适用于科学计算、图像处理等场景。相比多线程,多进程更适合利用多核优势,虽有较高内存开销,但能显著提升性能。合理使用进程池与通信机制,可最大化效率。
267 3
|
2月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
269 0
|
3月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的多面手
Python:现代编程的多面手
84 0
|
3月前
|
存储 人工智能 算法
Python实现简易成语接龙小游戏:从零开始的趣味编程实践
本项目将中国传统文化与编程思维相结合,通过Python实现成语接龙游戏,涵盖数据结构、算法设计与简单AI逻辑,帮助学习者在趣味实践中掌握编程技能。
337 0

推荐镜像

更多