@classmethod:装饰器 固定写法
类方法:
1.参数的书写问题,第一个参数一般写(cls)
2.加上装饰器,@classmethod标注为类方法。
调用:
1.类对象:类名.类方法名
2.实例对象:创建一个实例对象。实例对象.类方法的名
@classmethod的使用
class Person(object):
country='中国'#类属性
@classmethod#装饰器 固定写法
def countryInfo(cls):
print('此时已经调用了类方法')
def __init__(self,name,age,gender):
self.name=name
self.age=age
self.gender=gender
def personInfo(self):
print('姓名:',self.name,'年龄:',self.age,'性别:',self.gender)
if __name__ == '__main__':
#按照类对象进行调用
#类名.类方法的名
Person.countryInfo()
#使用实例对象调用
ming=Person('小明',18,'boy')
#初始化一个实例对象
#实例对象.类方法的名
ming.countryInfo()
@staticmethod.()静态方法,()内没有任何东西补充
可放在类外面写
类方法:
1.使用装饰器@staticmethod
2.就是类里面的普通函数,不用传self,cls
调用:
1.类对象:类名.类方法名
2.实例对象:创建一个实例对象。实例对象.类方法的名
类方法修改类属性以及@staticmethod的使用
class Hello(object):
#类方法修改类属性
gender="boy"
@classmethod
def helloInfo(cls):
print("这个人的性别:",cls.gender)
@classmethod
def changGender(cls,newgender):
cls.gender=newgender
print("现在这个人的性别:",cls.gender)
@staticmethod
def B():
print('有无数种人')
if __name__ == '__main__':
Hello.helloInfo()
Hello.changGender('boy')
Hello.changGender("boy and girl")
Hello.changGender("girl")
ming=Hello
ming.helloInfo()
ming.changGender("法国girl")