zoukankan      html  css  js  c++  java
  • 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、

  • 相关阅读:
    java中的工厂模式(简单工厂模式+工厂方法模式)
    代码集合
    java读取文件的路径问题
    使用ZXing库生成二维码
    java设计模式-装饰者模式
    android文件流缓存
    java8 新特性
    Excel导出
    常用的在线工具
    Java加密简介
  • 原文地址:https://www.cnblogs.com/hzgq/p/11890624.html
Copyright © 2011-2022 走看看