类相关的知识#
在python2中的区分:
经典类:
1
2
|
class
School:
pass
|
新式类:
1
2
|
class
School(
object
):
pass
|
在python3中以上两种均为新式类
属性:
- 数据属性:就是变量
- 函数属性:就是函数,在面向对象里通常称为方法
注:类和对象均用点来访问自己的属性
类的属性#
数据属性即变量,类的定义与函数又及其相似,其实可以用函数的作用域来理解类的属性调用
类的数据属性:
1
2
3
|
class
School:
Teacher
=
"老王"
print
(School.Teacher)
|
类的函数属性(一般称为方法):
1
2
3
4
5
|
class
School:
Teacher
=
"老王"
def
Examination(
self
):
print
(
"%s的班级正在考试"
%
self
)
School.Examination(
"alex"
)
|
查看类属性:
查看类属性的两种方式:
- dir(类名) 查出的是一个名字列表
- 类名.__dict__ 查出的是一个字典,key是属性名,value是属性值
#注意:类名加点调用自己的属性实际上就是到属性字典里去找东西
class School: Teacher = "老王" def Examination(self): print("%s的班级正在考试"%self) print(dir(School)) #查看类的属性 print(School.__dict__) #查看类的属性字典 print(School.Teacher)#同print(School.__dict__["Teacher"]) 调用数据属性 School.Examination("alex")#同School.__dict__["Examination"]("alex") 调用函数属性
特殊的类属性:
class School: """ 文档 """ Teacher = "老王" def Examination(self): print("%s的班级正在考试"%self) print(School.__name__) #查看类名 print(School.__doc__) #查看文档 print(School.__base__) #查看类的第一个父类 print(School.__bases__) #查看类所有父类构成的元组 print(School.__dict__) #查看类的属性 print(School.__module__) #查看类所在哪个模块 print(School.__class__) #实例School对应的类(仅新式类中)
对象相关知识#
对象是由类实例化而来,实例化结果成为一个实例或者称作一个对象
实例化:
class School: """ 文档 """ Teacher = "老王" def Examination(self): print("%s的班级正在考试"%self) School()