python中
@classmethod
classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法。但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Service(object):
service_name = "neutron"
def get_ip(self):
return ('1.1.1.1')
@classmethod
def get_mac(cls):
print (cls.service_name)
ipaddr = cls().get_ip()
print (ipaddr)
return('aa:bb:cc:dd:ee:ff')
mac = Service.get_mac()
print (mac)
输出:
neutron
1.1.1.1
aa:bb:cc:dd:ee:ff