python --- 类

1、

class Animal(object):
    def __init__(self):  #如果初始化函数有参数传入( def __init__(self,a,b)),则实例化的时候(animal = Animal(‘hi’,‘ha’))必须带参数
        self.type = 'dog'
        self.color = ''

    def voice(self):  #实例方法,传入self的方法
        if self.type == 'dog':
            print('可爱的{0}色小狗,汪汪汪!'.format(self.color))

    @classmethod  #类方法,没有像实例方法一样传入self,调用的时候无需依赖实例,同样也无法引用self.type,所以很少使用
    def dog(cls):
        print('所有的小狗都汪汪汪')

    @staticmethod  #静态方法,没有像实例方法一样传入self,调用的时候无需依赖实例,同样也无法引用self.type,所以很少使用
    def dog_color():
        print('dog 的颜色是 黑色 ')

# animal = Animal()  #Animal(),有括号的才是实例化
# animal.voice()
Animal.dog()  #类方法和实例方法都可通过类名直接调用
Animal.dog_color()

 

2、

 

posted @ 2019-11-19 17:00  红枣枸杞  阅读(132)  评论(0编辑  收藏  举报