Python编程:python面向对象

简介: 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']


相关文章
|
2天前
|
云安全 人工智能 自然语言处理
|
9天前
|
数据采集 人工智能 自然语言处理
Meta SAM3开源:让图像分割,听懂你的话
Meta发布并开源SAM 3,首个支持文本或视觉提示的统一图像视频分割模型,可精准分割“红色条纹伞”等开放词汇概念,覆盖400万独特概念,性能达人类水平75%–80%,推动视觉分割新突破。
662 56
Meta SAM3开源:让图像分割,听懂你的话
|
6天前
|
搜索推荐 编译器 Linux
一个可用于企业开发及通用跨平台的Makefile文件
一款适用于企业级开发的通用跨平台Makefile,支持C/C++混合编译、多目标输出(可执行文件、静态/动态库)、Release/Debug版本管理。配置简洁,仅需修改带`MF_CONFIGURE_`前缀的变量,支持脚本化配置与子Makefile管理,具备完善日志、错误提示和跨平台兼容性,附详细文档与示例,便于学习与集成。
320 116
|
6天前
|
人工智能 Java API
Java 正式进入 Agentic AI 时代:Spring AI Alibaba 1.1 发布背后的技术演进
Spring AI Alibaba 1.1 正式发布,提供极简方式构建企业级AI智能体。基于ReactAgent核心,支持多智能体协作、上下文工程与生产级管控,助力开发者快速打造可靠、可扩展的智能应用。
|
21天前
|
域名解析 人工智能
【实操攻略】手把手教学,免费领取.CN域名
即日起至2025年12月31日,购买万小智AI建站或云·企业官网,每单可免费领1个.CN域名首年!跟我了解领取攻略吧~
|
9天前
|
机器学习/深度学习 人工智能 自然语言处理
AgentEvolver:让智能体系统学会「自我进化」
AgentEvolver 是一个自进化智能体系统,通过自我任务生成、经验导航与反思归因三大机制,推动AI从“被动执行”迈向“主动学习”。它显著提升强化学习效率,在更少参数下实现更强性能,助力智能体持续自我迭代。开源地址:https://github.com/modelscope/AgentEvolver
447 32
|
5天前
|
弹性计算 人工智能 Cloud Native
阿里云无门槛和有门槛优惠券解析:学生券,满减券,补贴券等优惠券领取与使用介绍
为了回馈用户与助力更多用户节省上云成本,阿里云会经常推出各种优惠券相关的活动,包括无门槛优惠券和有门槛优惠券。本文将详细介绍阿里云无门槛优惠券的领取与使用方式,同时也会概述几种常见的有门槛优惠券,帮助用户更好地利用这些优惠,降低云服务的成本。
278 133

热门文章

最新文章