laityc 2020-03-01
#类的继承
class Animal(object): #Animal类继承object
def __init__(self,color):
self.color = color
def eat(self):
print("动物在吃!")
def run(self):
print("动物在跑")
class Cat(Animal): #Cat继承Aninal 继承[属性和方法]
pass
cat = Cat("白色")
print(cat.color)
cat.eat()上面定义Animal类,Animal类继承基类object,Animal类中有属性color和方法
Cat类继承Animal类,继承了属性和方法
#类的继承
class Animal(object): #Animal类继承object
def __init__(self,color):
self.color = color
def eat(self):
print("动物在吃!")
def run(self):
print("动物在跑")
class Cat(Animal): #Cat继承Aninal 继承[属性和方法]
pass
class Dog(Animal): #继承时候,方法重名用子方法
def __init__(self,name,age,color):
super(Dog,self).__init__(color) #super表示父类,调用父类的初始化方法
self.name = name
self.age = age
def eat(self): #方法重名
print("狗仔!")
dog = Dog("狗仔队",12,"黑色")现在根据上面的继承后,再次创建一个Dog类,定义了与Animal类重名的eat方法
使用super(className,self).__init__(color),super表示的是父类,让className继承父类的color属性,不需要再次重写属性
在实例化的过程中,传入参数,类的实例化传入的参数对象本身self就是一个参数
class Singleton: def __new__: # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象 if not hasattr: cls.instance =