在python中有3种方法:
class Person():
species='homo_sapiens' # This is class variable
def __init__(self, name, age):
self.name = name # This is instance variable
self.age = age
def show(self):
print('Name: {}, age: {}.'.format(self.name, date.today().year - self.age))
@classmethod
def create_with_birth_year(cls, name, birth_year):
return cls(name, date.today().year - birth_year)
@classmethod
def print_species(cls):
print('species: {}'.format(cls.species))
@staticmethod
def get_birth_year(age):
return date.today().year - age
class Teacher(Person):
pass
1)实例方法(
显示
)需要实例,必须使用
自己
作为第一个参数。它可以通过
自己
影响一个实例的状态。
2)分类法(
用出生年份创建
和
版画种
)无需实例和使用
CLS
访问类并影响类的状态。我们可以使用
@类方法
制造工厂,如:
navy = Person.create_with_birth_year('Navy Cheng', 1989)
navy.show()
和
这个工厂可以继承
:
zhang = Teacher.create_with_birth_year('zhang', 1980)
print(type(zhang))
类方法可以用来访问类变量:
Person.print_species()
3)静态法(
吉特诞辰年
)无需特殊参数(
自己
或
CLS
)并将更改类或实例的任何状态。它可以对类的一些助手函数进行私有化。