当前位置:首页 > 物联网 > Freak嵌入式

摘要:

在 Python 中,所有的类都直接或间接继承自一个根类,这个根类是Object。Object类是 Python 中所有新式类的基础类,在 Python 的类层次结构中,Object类是所有类的最终基类。

文档和代码获取:

本文档主要介绍如何使用 Python 进行面向对象编程,需要读者对 Python 语法和单片机开发具有基本了解。相比其他讲解 Python 面向对象编程的博客或书籍而言,本文档更加详细、侧重于嵌入式上位机应用,以上位机和下位机的常见串口数据收发、数据处理、动态图绘制等为应用实例,同时使用 Sourcetrail代码软件对代码进行可视化阅读便于读者理解。

正文

Python中常用的内置类型包括数字、序列、映射、类、实例和异常。内置数据类型是指在Python中预定义的基本数据类型,包括字符串(str)、列表(list)、元组(tuple)以及字典(dict)等。

对于Python来说,所有的数据类型都继承于object类,object类定义如下:

class object |  The base class of the class hierarchy. | |  When called, it accepts no arguments and returns a new featureless |  instance that has no instance attributes and cannot be given any. | |  Built-in subclasses: |      anext_awaitable |      async_generator |      async_generator_asend |      async_generator_athrow |      ... and 90 other subclasses | |  Methods defined here: | |  __delattr__(self, name, /) |      Implement delattr(self, name). | |  __dir__(self, /) |      Default dir() implementation. | |  __eq__(self, value, /) | Return self==value. | |  __format__(self, format_spec, /) |      Default object formatter. | | Return str(self) if format_spec is empty. Raise TypeError otherwise. | |  __ge__(self, value, /) | Return self>=value. | |  __getattribute__(self, name, /) | Return getattr(self, name). | | |  __getstate__(self, /) |      Helper for pickle. | |  __gt__(self, value, /) | Return self>value. | |  __hash__(self, /) | Return hash(self). | |  __init__(self, /, *args, **kwargs) |      Initialize self.  See help(type(self)) for accurate signature. | |  __le__(self, value, /) | Return self<=value. | |  __lt__(self, value, /) | Return self | |  __ne__(self, value, /) | Return self!=value. | |  __reduce__(self, /) |      Helper for pickle. | |  __reduce_ex__(self, protocol, /) |      Helper for pickle. | |  __repr__(self, /) | Return repr(self). | |  __setattr__(self, name, value, /) |      Implement setattr(self, name, value). | |  __sizeof__(self, /) |      Size of object in memory, in bytes. | |  __str__(self, /) | Return str(self). | | |  ---------------------------------------------------------------------- | |  Class methods defined here: | |  __init_subclass__(...) from builtins.type |      This method is called when a class is subclassed. | |      The default implementation does nothing. It may be |      overridden to extend subclasses. | |  __subclasshook__(...) from builtins.type |      Abstract classes can override this to customize issubclass(). | |      This is invoked early on by abc.ABCMeta.__subclasscheck__(). |      It should return True, False or NotImplemented. If it returns |      NotImplemented, the normal algorithm is used.  Otherwise, it |      overrides the normal algorithm (and the outcome is cached). | |  ---------------------------------------------------------------------- |  Static methods defined here: | |  __new__(*args, **kwargs) from builtins.type |      Create and return a new object.  See help(type) for accurate signature. | |  ---------------------------------------------------------------------- | Data and other attributes defined here: | |  __class__ = 'type'> |      type(object) -> the object's type |      type(name, bases, dict, **kwds) -> a new type

简单来说,object是Python中所有类的基类。它是一个内置的根类,其他所有类都隐式地或显式地继承自它。如果一个类在定义中没有明确定义继承的基类,那么默认就会继承object.__mro__ 属性记录类继承的关系,它是一个元组类型,从结果可以看出 Employee 继承自 object 基类。

class Employee(): pass# 等价于class Employee(object): pass# 打印类的继承关系print(Employee.__mro__)

object类为所有对象提供了通用的方法和属性,典型方法如下:

类型

名称

作用

构造函数

__init__

object类的构造函数,虽然没有特别有用的功能,但在子类中定义自己的构造函数时,需要调用super().__init__()来确保object类的初始化被执行。

字符串表示方法

__str__

object类定义了用于返回对象字符串表示的方法。可以在子类中重写这个方法来自定义对象的字符串表示。

属性访问方法

__getattr__

__setattr__

__delattr__

这些方法允许在属性被访问或设置时插入自定义的行为。当属性不存在时,__getattr__会被调用。__delattr__,用于 del 语句,删除类或者对象的某个属性。通过它们我们可以对任意一个我们不熟悉的对象进行尝试性访问,而不会导致程序出错。

对象比较方法

__eq__

__ne__

这些方法用于定义对象之间的相等性和不相等性。默认情况下,它们比较对象的标识,但可以在子类中进行自定义。

哈希方法

__hash__

用于定义对象的哈希值,通常与字典、集合等数据结构相关。

布尔值方法

__bool__

定义对象的布尔值,通常用于条件语句中。

帮助类方法

__dir__

__doc__

__dir__() 方法用于类的所有属性和方法名,它是一个字典,内置函数 dir() 就是对它的调用。

__doc__ 属性指向当前类的描述字符串。描述字符串是放在类定义中第一个未被赋值的字符串,它不会被继承

我们可以不用创建子类,直接实例化object:

o = object()o.x = 5

怎么回事,为什么会报错?原来直接实例化的 object 无法设定任何属性。由于需要节省内存,Python 默认禁止向 object 以及其他几个内置类型添加任意属性。object类作为Python中所有类的根类,其作用是为其他类的创建和使用提供了基础。

实际上,类的实例也可以作为父类/基类。接下来,我们将通过详细阐述一下object类和Type类型间的关系帮助大家加深对于类、对象和实例之间关系的理解。


本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
关闭