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

    python类方法的注意点

    小妮浅浅小妮浅浅2021-10-19 10:30:13原创5819

    1、@classmethod必须在方法上面。

    2、第一个cls必须有,指的是类对象本身。

    3、在类方法中访问实例属性和实例方法会导致错误。

    4、当子类继承父类方法时,cls是子类对象,而不是父类对象。

    调用类方法格式:“类名.类方法名(参数列表)”。

    参数列表中不与要也不能 cls 传值。

    实例

    class Person:
     
        # 类属性
        school = "中加枫华国际学校"
        tuition = 100000
        count = 0
     
        # 实例属性
        def __init__(self,name,age,gender):
            self.name = name
            self.age = age
            self.gender = gender
            Person.count = Person.count+1
     
        @classmethod
        def printSchool(cls):
            print(cls)
            print(cls.school)
     
        # 实例方法
        def get_score(self):
            print("姓名:{0};年龄:{1};性别:{2}".format(self.name,self.age,self.gender))
     
    stu1 = Person("sue", 22, "male")
    stu1.get_score()
    Person.printSchool()

    以上就是python类方法的注意点,希望对大家有所帮助。更多Python学习指路:python基础教程

    专题推荐:python 类方法
    品易云
    上一篇:python实例方法的使用注意 下一篇:python静态方法的用法

    相关文章推荐

    • python TKinter普通菜单的介绍• python TKinter弹出式菜单的使用• python canvas画布的介绍• python中sys.argv模块的介绍• python中getopt模块是什么• python中argparse库是什么• python如何委派生成器• python闭包的特点• python中AttributeError异常的介绍• python列表访问的方法• python生成器推导式是什么• python字典添加值的方法• python序列解包的使用• python模块的name属性• python实例方法的使用注意

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网