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']
相关文章
|
6月前
|
机器学习/深度学习 存储 设计模式
Python 高级编程与实战:深入理解性能优化与调试技巧
本文深入探讨了Python的性能优化与调试技巧,涵盖profiling、caching、Cython等优化工具,以及pdb、logging、assert等调试方法。通过实战项目,如优化斐波那契数列计算和调试Web应用,帮助读者掌握这些技术,提升编程效率。附有进一步学习资源,助力读者深入学习。
|
3月前
|
Python
Python编程基石:整型、浮点、字符串与布尔值完全解读
本文介绍了Python中的四种基本数据类型:整型(int)、浮点型(float)、字符串(str)和布尔型(bool)。整型表示无大小限制的整数,支持各类运算;浮点型遵循IEEE 754标准,需注意精度问题;字符串是不可变序列,支持多种操作与方法;布尔型仅有True和False两个值,可与其他类型转换。掌握这些类型及其转换规则是Python编程的基础。
210 33
|
2月前
|
数据采集 分布式计算 大数据
不会Python,还敢说搞大数据?一文带你入门大数据编程的“硬核”真相
不会Python,还敢说搞大数据?一文带你入门大数据编程的“硬核”真相
82 1
|
3月前
|
设计模式 安全 Python
Python编程精进:正则表达式
正则表达式是一种强大的文本处理工具,用于搜索、匹配和提取模式。本文介绍了正则表达式的语法基础,如`\d`、`\w`等符号,并通过实例展示其在匹配电子邮件、验证电话号码、处理日期格式等场景中的应用。同时,文章提醒用户注意性能、编码、安全性等问题,避免常见错误,如特殊字符转义不当、量词使用错误等。掌握正则表达式能显著提升文本处理效率,但需结合实际需求谨慎设计模式。
135 2
|
4月前
|
数据采集 安全 BI
用Python编程基础提升工作效率
一、文件处理整明白了,少加两小时班 (敲暖气管子)领导让整理100个Excel表?手都干抽筋儿了?Python就跟铲雪车似的,哗哗给你整利索!
114 11
|
6月前
|
人工智能 Java 数据安全/隐私保护
[oeasy]python081_ai编程最佳实践_ai辅助编程_提出要求_解决问题
本文介绍了如何利用AI辅助编程解决实际问题,以猫屎咖啡的购买为例,逐步实现将购买斤数换算成人民币金额的功能。文章强调了与AI协作时的三个要点:1) 去除无关信息,聚焦目标;2) 将复杂任务拆解为小步骤,逐步完成;3) 巩固已有成果后再推进。最终代码实现了输入验证、单位转换和价格计算,并保留两位小数。总结指出,在AI时代,人类负责明确目标、拆分任务和确认结果,AI则负责生成代码、解释含义和提供优化建议,编程不会被取代,而是会更广泛地融入各领域。
185 28
|
6月前
|
机器学习/深度学习 数据可视化 TensorFlow
Python 高级编程与实战:深入理解数据科学与机器学习
本文深入探讨了Python在数据科学与机器学习中的应用,介绍了pandas、numpy、matplotlib等数据科学工具,以及scikit-learn、tensorflow、keras等机器学习库。通过实战项目,如数据可视化和鸢尾花数据集分类,帮助读者掌握这些技术。最后提供了进一步学习资源,助力提升Python编程技能。
|
6月前
|
设计模式 机器学习/深度学习 前端开发
Python 高级编程与实战:深入理解设计模式与软件架构
本文深入探讨了Python中的设计模式与软件架构,涵盖单例、工厂、观察者模式及MVC、微服务架构,并通过实战项目如插件系统和Web应用帮助读者掌握这些技术。文章提供了代码示例,便于理解和实践。最后推荐了进一步学习的资源,助力提升Python编程技能。
|
6月前
|
Python
[oeasy]python074_ai辅助编程_水果程序_fruits_apple_banana_加法_python之禅
本文回顾了从模块导入变量和函数的方法,并通过一个求和程序实例,讲解了Python中输入处理、类型转换及异常处理的应用。重点分析了“明了胜于晦涩”(Explicit is better than implicit)的Python之禅理念,强调代码应清晰明确。最后总结了加法运算程序的实现过程,并预告后续内容将深入探讨变量类型的隐式与显式问题。附有相关资源链接供进一步学习。
86 4
|
6月前
|
数据采集 搜索推荐 C语言
Python 高级编程与实战:深入理解性能优化与调试技巧
本文深入探讨了Python的性能优化和调试技巧,涵盖使用内置函数、列表推导式、生成器、`cProfile`、`numpy`等优化手段,以及`print`、`assert`、`pdb`和`logging`等调试方法。通过实战项目如优化排序算法和日志记录的Web爬虫,帮助你编写高效稳定的Python程序。

热门文章

最新文章

推荐镜像

更多