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的一切万物皆对象的思想。