三种方法的区别:
1 实例方法:方法一个参数是self,必须通过实例化的对象去调用。
2 类方法,要加上@classmethod来声明,参数至少有一个,第一个参数一般定义为cls,使用类变量,不能使用实例变量。通过类名或者实例对象调用。
3 静态方法,要加上@staticmethod来声明,可以没有参数,可以用实例或者类名去调用,方法里面可以使用类变量,不能使用实例变量。
不想做实例化,且只操作类变量:类方法、静态方法
如果想使用实例变量,只能使用实例方法了。
class Person:
count = 0 # 类变量
nation = "中国"
def __init__(self, name, gender):
self.name = name
self.gender = gender
Person.count += 1
def get_name(self): # 实例方法,必须要实例化
return self.name
# 类方法:可以使用类变量,不能使用实例变量
# 通过类名来使用,类名.get_instance_count()
# 也可以通过实例调用,实例对象.get_instance_count()
@classmethod
def get_instance_count(cls):
return Person.count # 可用cls替换类名Person
@classmethod
def create_a_instance(cls):
return Person("张", "女")
@staticmethod # 静态方法:不需要self和cls
def get_nation():
return Person.nation
print(Person("老王", "Male").get_name())
laowang = Person("老王", "Male") # 实例化
print(laowang.get_name())
print(Person.count)
Person("老王", "Male")
print(Person.count)
print(Person.get_instance_count())
print(Person.create_a_instance())
print(Person("老王", "Male").get_instance_count())
print(Person.get_nation())
print(Person("老王", "Male").get_nation())