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

    python类属性设置默认值

    小妮浅浅小妮浅浅2021-06-15 10:21:17原创7612

    类属性说明

    1、类中的所有属性都必须有初始值,即使这个值是0或空字符串。

    2、在某些情况下,设定默认值时,在方法__init_()内指定该初始值是可行的,如果对某个属性进行这样的话,就不需要提供初始值的形参。

    实例

    class Cat():
        def __init__(self, name, color):
            self.name = name
            self.color = color
            self.age = 3
     
        def eat(self):
            print('cat ' + self.name + ' color ' + self.color + ', now eat')
     
        def run(self):
            print('cat ' + self.name + ' color ' + self.color + ', now run')
     
        def print_age(self):
            print('cat`s age is ' + str(self.age))

    以上就是python类属性设置默认值的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python 类属性
    品易云
    上一篇:python编写函数的注意点 下一篇:python导入类的不同方式

    相关文章推荐

    • Python3中类属性slots的常见疑问有哪些?• python中使用__slots__定义类属性• python继承的基类属性分析

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网