Python 的面向对象
下面我们介绍 Python 特有的关于面向对象的一些特性。
一切皆为对象
在 Python 中,一切皆为对象。
- 数字、字符串、列表、元组、字典等基本数据类型是对象。
- 函数、类、模块等也是对象。
- 基本数据类型等类本身也是对象。
它们都是
object类的实例。
变量引用对象
变量名是对对象的引用,而不是对象本身。 可迭代对象(如列表、元组、字符串)的内容是对多个对象的引用。
运算符也是函数
运算符(如 +、-、*、/、%)都是函数,它们的作用是调用前一个对象的特定方法,并返回一个新的对象。
举个例子,当你运行 a = 1 + 2 时, Python 解释器会创建整型对象 1 和 2,并查找整型 1 的方法 __add__(self, other),然后 1 作为 self 参数,2 作为 other 参数,调用该方法创建整型对象 3 并返回,然后根据赋值语句 a = ,将结果赋值给变量 a。
x = 1
y = 2
add = int.__add__
a = add(x, y)
print(add)
print(a)
<slot wrapper '__add__' of 'int' objects>
3文档
紧贴 class 语句下方的注释是文档注释,可以用 class.__doc__ 访问。
class Class:
"Something to say here."
print (Class.__doc__)
Something to say here.构造方法
Python 的类实例化与函数调用方式相同。具体地,调用一个类时,它的构造方法 __init__() 将被调用,然后返回其实例。
class Class:
def __init__(self, x):
print("Constructor called with x =", x)
print(Class(10))
Constructor called with x = 10
<__main__.Class object at 0x000001CB8B99C320>魔法方法
魔法方法是Python中一种特殊的函数,它有特殊的用途,可以让Python对象在特殊的情况下执行一些操作。
通常,魔法方法以两个下划线开头和结尾,比如__init__、__str__、__add__、__del__、__len__、__getitem__、__call__等。
class Class:
def __str__(self):
return "This is a class"
def __len__(self):
return 10
def __add__(self, other):
return "adding" + str(other)
def __getitem__(self, index):
return "getting item at index " + str(index)
def __call__(self, x):
return "calling with " + str(x)
def __del__(self):
print(f"deleting")
c = Class()
print(c)
print(len(c))
print(c + " something else")
print(c[3])
print(c(5))
del c
This is a class
10
adding something else
getting item at index 3
calling with 5
deleting