搞懂Python类继承的用法
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def printinfo(self):
print("name is %s , age is %d " %(self.name,self.age))
# 实现特定功能的多行代码使用 Animal 来创建对象,然后执行 printinfo 方法:
x = Animal("dog", 6)
x.printinfo()
name is dog , age is 6
class Cat(Animal):
pass
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def printinfo(self):
print("name is %s , age is %d " %(self.name,self.age))
class Cat(Animal):
pass # 实现特定功能的多行代码使用 Animal 来创建对象,然后执行 printinfo 方法:
x = Cat("cat", 8)
x.printinfo()
name is cat , age is 8
class Cat(Animal):
def __init__(self, name, age):
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def printinfo(self):
print("name is %s , age is %d " %(self.name,self.age))
class Cat(Animal):
def __init__(self, name, age):
Animal.__init__(self, name, age)
x = Cat("cat", 10)
x.printinfo()
name is cat , age is 10
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def printinfo(self):
print("name is %s , age is %d " %(self.name,self.age))
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name, age)
x = Cat("cat", 12)
x.printinfo()
name is cat , age is 12
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def printinfo(self):
print("name is %s , age is %d " %(self.name,self.age))
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name, age)
self.color = "block"
x = Cat("cat", 12)
print("name is %s , age is %d , color is %s" %(x.name,x.age,x.color))
name is cat , age is 12 , color is block
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def printinfo(self):
print("name is %s , age is %d " %(self.name,self.age))
class Cat(Animal):
def __init__(self, name, age,color):
super().__init__(name, age)
self.color = color
x = Cat("cat", 12,"block")
print("name is %s , age is %d , color is %s" %(x.name,x.age,x.color))
name is cat , age is 12 , color is block
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def printinfo(self):
print("name is %s , age is %d " %(self.name,self.age))
class Cat(Animal):
def __init__(self, name, age,color):
super().__init__(name, age)
self.color = "block"
def say(self):
print("name is %s , age is %d , color is %s" %(self.name,self.age,self.color))
x = Cat("cat", 12,"block")
x.say()
name is cat , age is 12 , color is block