首页 > 编程语言 > 详细

python --- 类

时间:2019-11-19 17:56:14      阅读:79      评论:0      收藏:0      [点我收藏+]

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、

 

python --- 类

原文:https://www.cnblogs.com/hzgq/p/11890624.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!