标签:python python类的属性
1.类属性分类class Door():
"门的类"
address = "浙江省杭州市"
def __init__(self,size,color,type):
"初始化门的数据"
self.size = size
self.color = color
self.type = type
def open(self):
"门打开的方法"
print("这个%s门打开了" %self.type)
def off(self):
"门关闭的方法"
print("这个%s门关闭了" %self.type)
print(Door.__dict__)
所以获取类的属性有两种方法:
① 使用英文点(.)来调用属性,如下图所示:
代码块如下:
class Door():
"门的类"
address = "浙江省杭州市"
def __init__(self,size,color,type):
"初始化门的数据"
self.size = size
self.color = color
self.type = type
def open(self):
"门打开的方法"
# print("这个%s门打开了" %self.type)
print("这个门打开了")
def off(self):
"门关闭的方法"
print("这个%s门关闭了" %self.type)
#类的数据属性
print("门的出产地为:", Door.address)
#类的函数属性
Door.open(‘self‘) #实参任意填
② 使用类的属性字典来调用属性,如下图所示:
代码块如下:
class Door():
"门的类"
address = "浙江省杭州市"
def __init__(self,size,color,type):
"初始化门的数据"
self.size = size
self.color = color
self.type = type
def open(self):
"门打开的方法"
# print("这个%s门打开了" %self.type)
print("这个门打开了")
def off(self):
"门关闭的方法"
# print("这个%s门关闭了" %self.type)
print("这个门关闭了" )
#类的数据属性,方法一
# print("门的出产地为:", Door.address)
#类的函数属性
# Door.open(‘self‘) #实参任意填
#类的数据属性,方法二
addr = Door.__dict__[‘address‘]
print("门的出产地为:", addr)
Door.__dict__[‘open‘](‘铝合金‘)
Door.__dict__[‘off‘](‘铝合金‘)
③ 总结
方法一实际上是调用方法二,即直接用点来调用类的属性时是先调用类的属相字典,在取出对应的结果。
3.类的其他特殊属性
代码块如下:
class Door():
"门的类"
address = "浙江省杭州市"
def __init__(self,size,color,type):
"初始化门的数据"
self.size = size
self.color = color
self.type = type
def open(self):
"门打开的方法"
# print("这个%s门打开了" %self.type)
print("这个门打开了")
def off(self):
"门关闭的方法"
# print("这个%s门关闭了" %self.type)
print("这个门关闭了" )
print(Door.__name__) #类的名字
print(Door.__doc__) #类的文档
print(Door.__base__) #类继承的第一个父类
print(Door.__bases__) #类继承的父类组成的元组
print(Door.__dict__) #类的属性字典
print(Door.__module__) #类定义所在的模块
标签:python python类的属性
原文地址:http://blog.51cto.com/10836356/2108780