浅谈python的对象思想和表现

本文介绍了Python中一切皆对象的概念,通过展示list和int等基本数据类型的类定义,揭示了Python如何将所有内容划分为类及其实例。文章强调Python的源码中,这些基本类型都是基于类的对象,比如list类继承自object,并提供了append、clear等方法。通过对Python内置类型的源码分析,进一步阐述了Python的面向对象特性。
摘要由CSDN通过智能技术生成

python中的面对对象思想



前言

你可以这样理解,python中的一切皆对象。


一、常见的数据类型

Number(数字)
String(字符串)
List(列表)
Tuple(元组)
Set(集合)
Dictionary(字典)

Number(数字)

在python3中支持的数字类型有下面三种,
int 整型
float 浮点型
complex 复数

为什么说在python中一切万物皆对象呢?

因为所有的东西都被划分成一种类了,而具体的某个特定的东西是某个类的实例化对象。

所幸我们能看到python的源码,我们直接上代码。

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -> None -- append object to end """
        pass

    def clear(self): # real signature unknown; restored from __doc__
        """ L.clear() -> None -- remove all items from L """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ L.copy() -> list -- a shallow copy of L """
        return []

如上就是python源码中对 list类的定义。

我们在使用定义一个列表对象的时候其实就是在调用这里的list类对其实例化成某个特定的对象。
其他也一样,

class int(object):
    """
    int(x=0) -> integer
    int(x, base=10) -> integer
    
    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is a number, return x.__int__().  For floating point
    numbers, this truncates towards zero.
    
    If x is not a number or if base is given, then x must be a string,
    bytes, or bytearray instance representing an integer literal in the
    given base.  The literal can be preceded by '+' or '-' and be surrounded
    by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
    Base 0 means to interpret the base from the string as an integer literal.
    >>> int('0b100', base=0)
    4
    """
    def bit_length(self): # real signature unknown; restored from __doc__
        """
        int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        6
        """
        return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ Returns self, the complex conjugate of any int. """
        pass

其他的也是一个道理,感兴趣的话,可以找到python的builtins.py这个文件,我们搜索对应的数据类型,都能找到对应的一个类。

此外,这里面定义的类都继承了一个object类,再次展现了python的一切万物皆对象的思想。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老师好,我是刘同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值