• 技术文章 >Python技术 >Python基础教程

    python类的两种属性

    小妮浅浅小妮浅浅2021-08-19 09:32:04原创2947

    两种属性

    1、内置类属性:Python类中存在各种内置属性。

    例如_dict_、_doc_、_name _ 等。举例,想查看employee1 的所有键值对。可以简单地编写以下包含类命名空间的语句:

    打印(emp_1.__dict__)

    2、用户定义的属性:属性是在类定义中创建的。可以为类的现有实例动态创建新属性。属性也可以绑定到类名。

    实例

    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电脑。

    专题推荐:python类
    品易云
    上一篇:python旋转图片和压缩像素的方法 下一篇:python中%格式表达式如何使用

    相关文章推荐

    • python类可以传递参数吗• python类装饰器的使用注意• python类 是什么• python类装饰器如何使用?• Python类成员的访问限制• python类属性设置默认值• python类变量和实例变量的对比• python类如何实例化对象• python类方法如何定义• python类的继承如何定义?• python类的继承链分析• python类实例化如何实现• Python类属性如何使用• python类如何自定义实例化

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网