柠檬班 2019-11-04
1、类animal = Animal(‘汪‘),animal叫对象;变量叫属性
class Animal(object): voice = ‘咩‘ def __init__(self,voice): #__init__为python内置函数 Animal.voice = voice #直接对类的属性进行修改 def cat(self): pass print(Animal.voice) animal = Animal(‘汪‘) #Animal为一个类型,animal为用类型创建出来的对象 print(Animal.voice) animal2 = Animal(‘喵‘) print(animal.voice) print(animal2.voice) print(Animal.voice) 控制台输出: 咩 汪 喵 喵 喵
2、由1所知Animal.voice = voice为直接对类的属性进行修改,那么如何只对对象的属性进行修改,而不影响其它创建的对象呢
class Animal(object): voice = ‘咩‘ def __init__(self,voice): self.voice = voice #self.voice代表实例化后的对象 def cat(self): pass print(Animal.voice) animal = Animal(‘汪‘) print(Animal.voice) animal2 = Animal(‘喵‘) print(animal.voice) #self.voice这种的,当发现self(对象)里面没有这种能力的时候,才会到Animal这个类型里去找;如果Animal这个类里没有,会到Animal的基类内找 print(animal2.voice) print(Animal.voice) 控制台输出: 咩 咩 汪 喵 咩
3、
4、
class Singleton: def __new__: # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象 if not hasattr: cls.instance =