
引言
Java语言也是面向对象的语言,但是Python要更加彻底
Python的面向对象特性,是它使用起来灵活的根本所在
对象的特点
可以赋值给一个变量
1 2 3 4 5 6 | # 函数也是对象
def test(name):
print(name)
my_func = test # 注意 只写函数名 和 函数名加括号 的区别
my_func("MetaTian") # 打印:MetaTian
|
可以添加到集合中去
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | def plus(a, b):
print(a+b)
def minus(a, b):
print(a-b)
fun_list = []
fun_list.append(plus)
fun_list.append(minus)
for item in fun_list:
item(2, 1)
# result:
# 3
# 1
|
可以作为参数传递给函数
1 2 3 4 5 6 7 8 9 10 | def plus(a, b):
print(a+b)
def calculate(method, a, b):
method(a, b)
calculate(plus, 1, 2)
# result:
# 3
|
可以当做函数的返回值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # 这也是装饰器的原理
def inner():
print("MetaTian")
def deco():
print("decorating...")
return inner
my_func = deco()
my_func()
# result:
# decorating...
# MetaTian
|
对象的3个属性
身份:在内存中的地址是多少,可用id()函数查看
类型:是什么类型的对象,可用type()函数查看
值:对象中的内容是什么
type object和class的关系
type和class
关系:type -> class -> obj,obj是我们平时使用的对象,它由class对象生成,可以是我们自定义的类,也可以是内建的类。上面说了,一切皆对象,class也是以type为模板,生成的对象。
type()函数,当传入一个参数时,返回对象的类型。传入三个参数时,用来生成一个类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | print(type(1))
print(type(int))
# result:
# < class 'int'>
# < class 'type'>
class Person:
pass
student = Person()
print(type(student))
print(type(Person))
# result:
# < class '__main__.Person'>
# < class 'type'>
print(type(type))
# result:
# < class 'type'>
|
type是以它自己为类生成的一个对象。如果熟悉静态语言,这似乎并不好理解,但是对动态语言来说就是这么自然。
object
object是最根本的一个基类,如果自己定义的类没有显示地去继承某一个类,则它会自动继承object。上面讨论的是类和对象之间的关系,现在要讨论的是类和类之间的关系。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Person:
pass
class Student(Person):
pass
print(Student.__bases__)
print(Person.__bases__)
print(int.__bases__)
print(object.__bases__)
# result:
# (< class '__main__.Person'>,)
# (< class 'object'>,)
# (< class 'object'>,)
# ()
print(type.__bases__)
print(type(object)
# result:
# (< class 'object'>,)
# < class 'type'>
|
type是一个类,它继承的是object,object作为一个对象又是以type为类型生成的。