为了账号安全,请及时绑定邮箱和手机立即绑定

定义类方法中的参数为啥是cls

定义的类方法中的参数cls 是什么意思?必须要用cls作参数么

正在回答

2 回答

对于类方法,第一个参数必须是类对象,一般以"cls"作为第一个参数(当然可以用其他名称的变量作为其第一个参数,但是大部分人都习惯以'cls'作为第一个参数的名字,就最好用'cls'了)

0 回复 有任何疑惑可以回复我~
#1

饮一杯岁月留香 提问者

谢谢!
2016-03-30 回复 有任何疑惑可以回复我~
class people:
    country = 'china'
    
    #类方法,用classmethod来进行修饰    @classmethod    def getCountry(cls):        return cls.country

p = people()print p.getCountry()    #可以用过实例对象引用print people.getCountry()    #可以通过类对象引用

类方法还有一个用途就是可以对类属性进行修改:

class people:
    country = 'china'
    
    #类方法,用classmethod来进行修饰    @classmethod    def getCountry(cls):        return cls.country
        
    @classmethod    def setCountry(cls,country):
        cls.country = country
        

p = people()print p.getCountry()    #可以用过实例对象引用print people.getCountry()    #可以通过类对象引用p.setCountry('japan')   

print p.getCountry()   
print people.getCountry()

运行结果:

china
china
japan
japan


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
python进阶
  • 参与学习       255739    人
  • 解答问题       2946    个

学习函数式、模块和面向对象编程,掌握Python高级程序设计

进入课程

定义类方法中的参数为啥是cls

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信