类方法,实例方法,静态方法


类方法:

   定义:使用装饰器@classmethod,第一个参数必须是当前类对象,该参数一般是cls,通过它来传递类的属性和方法。

   调用:实例对象和类对象都可以调用

实例方法:

   定义:第一个参数必须是实例对象,该参数名一般是self,通过它来传递实例的对象和属性。

   调用:只能由实例对象来调用。

静态方法:

   定义:使用装饰器@staticmethod,参数随意,但是方法体重不能是用类和实例的任何属性和方法。

   调用:实例对象和类对象都可以调用。

eg:

class Dog:
dogbook = {'黄色': 30, '黑色': 20, '白色': 0}

def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight
"""实例化方法,定义时把self作为第一个参数,可以访问实例变量,只能通过实例名访问"""
def bark(self):
print(f'{self.name}叫起来了')
"""类方法,定义时把cls作为第一个参数,可以访问类变量,可以通过实例名或者类名访问"""
@classmethod
def dog_num(cls):
num = 0
for v in cls.dogbook.values():
num = num + v
return num
"""静态方法,没有参数限制,不能访问类变量和实例变量,即不能使用类属性和实例属性和方法,可以通过实例名或者类名访问"""
@staticmethod
def total_weight(dogs):
total = 0
for i in dogs:
total = total + i.weight
return total


print(f'共有{Dog.dog_num()}条狗')
dog1 = Dog('大黄', '黑色', 10)
dog1.bark()
print(f'共有{dog1.dog_num()}条狗')

dog2 = Dog('旺财', '黑色', 8)
dog2.bark()
print(f'狗共重{Dog.total_weight([dog1, dog2])}公斤')