Python的类方法,静态方法,实例方法,类变量,实例变量,静态变量的总结
在一些博客上面看到说Python没有静态变量,但是静态方法却是有的,这点我也弄的不大清楚,这个例子对于++类方法++,==静态方法==,实例方法的说明比较清楚,还有就是类变量和实例变量也比较明晰,希望在“静态变量”这个问题上和大家互相交流。
class CCC:
auth = "hello" # 类变量
def __init__(self):
self.person = "jzm123" # 实例变量
def instance_printauth(self): # 实例方法
print("成员方法:" + self.auth)
@classmethod
def class_printauth(cls): # 类方法
print("类方法:" + cls.auth)
@staticmethod
def static_printauth(): # 静态方法
print("静态方法:" + CCC.auth)
def use_membervariable(self):
print("成员变量" + self.person)
if __name__ == "__main__":
ccc = CCC()
print("---静态方法,对参数无要求---")
ccc.static_printauth()
CCC.static_printauth()
print("---类方法,第一个参数为类,可由类或者对象调用---")
ccc.class_printauth()
CCC.class_printauth()
print("---成员方法,只能由对象调用---")
ccc.instance_printauth()
print("---类变量---")
print("类变量:CCC.auth=" + CCC.auth) # 类变量
print("---实例变量---")
print("实例变量:ccc.person=" + ccc.person) # 实例变量
ccc.person = "xxx"
ccc.auth = "1222er"
print("实例变量:ccc.person=" + ccc.person) # 实例变量
print("类变量:CCC.auth=" + CCC.auth) # 类变量
CCC.auth = "ggg"
print("类变量:CCC.auth=" + CCC.auth) # 类变量
ppp = CCC()
print("实例变量:ppp.person=" + ppp.person) # 实例变量
print("类变量:CCC.auth=" + CCC.auth) # 类变量
下面是运行效果: