码迷,mamicode.com
首页 > 编程语言 > 详细

Python_类的属性

时间:2018-04-28 14:01:47      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:python   python类的属性   

1.类属性分类
类的属性分为:
?数据属性:就是类中的变量;
?函数属性:就是类中函数,在面向对象设计中通常称为方法;
?类和对象的属性均使用点(.)来访问自己的属性
2.类的属性
类的定义与函数极其相似,我们可以使用函数的作用域来理解类的属性调用方式。
我们可以通过类的属性字典来查询类的属性,如下图所示:
技术分享图片
代码块为:

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   python类的属性   

原文地址:http://blog.51cto.com/10836356/2108780

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!