
两种属性
1、内置类属性:Python类中存在各种内置属性。
例如_dict_、_doc_、_name _ 等。举例,想查看employee1 的所有键值对。可以简单地编写以下包含类命名空间的语句:
打印(emp_1.__dict__)
2、用户定义的属性:属性是在类定义中创建的。可以为类的现有实例动态创建新属性。属性也可以绑定到类名。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | class ClassDef(object):
def __init__(self):
# public
self.name = "class_def"
# private
self.__age = 29
# protected
self._sex = "man"
def fun1(self):
print( "call public function" )
def __fun2(self):
print( "call private function" )
def _fun3(self):
print( "call protected function" )
if __name__ == "__main__" :
# 实例化类对象
class_def = ClassDef()
# 调用方法
# ok
class_def.fun1()
class_def._ClassDef__fun2()
class_def._fun3()
# 访问数据
print(class_def._ClassDef__age)
print(class_def._sex)
print(class_def.name)
# error
# class_def.__fun2()
# print(class_def.__age)
|
以上就是python类的两种属性,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。