类的继承
1.私有属性不能被继承
例:
class Animal(object):
def __init__(self, name='animal', color='white'):
self.__name = name
self.__color = color
def __del__(self):
print('啊。。。。。。')
class Dog(Animal):
def __del__(self):
print(self.__name)
dog = Dog(name='旺财')
print(dog)
2.私有方法不能被继承
例:
class Animal(object):
def __init__(self, name='animal', color='white'):
self.name = name
self.color = color
def __showName(self):
print(self.name)
class Dog(Animal):
def test(self):
self.__showName()
one = Dog(name='旺财')
one.test()
3.调用父类的方法
例:
class Animal(object):
def __init__(self, name='animal', color='white'):
self.name = name
self.color = color
def test(self):
print('啊。。。。。。。。。')
class Cat(Animal):
def test1(self):
super().test()
Animal.test(self)
one = Cat(name='wangcai')
one.test1()
4.多继承–>广度遍历寻找方法
1) 广度遍历
2) 深度遍历
例:
class Base(object):
def test(self):
print('----------base test---------')
class A(base):
def testA(self):
print('----------A test------------')
def test(self):
print('-----------A test------------')
class B(Base):
def testB(self):
print('------------B test-------')
def test(self):
print('------------B test-----------')
class C(A,B):
pass
c = C()
c.test()
# 查看搜索顺序
print(c.__mro__())
5.类对象---->类属性
实例对象---->实例属性
例
class Animal(object):
def __init__(self, name='animal', color='white'):
self.name = name #实例属性
self.color = color
class Hourse(Animal): #类对象
hourseNum = 0 #类属性
def __init__(self, name='') #实例方法:
super().__init__(name)
self.setHoursenum()
@classmethed #类方法
def setHoursenum(cls):
hourseNum += 1
汗血宝马 = Hourse(name='汗血宝马')
print(Hourse.hourseNum)
赤兔马 = Hourse(name='赤兔马')
print(赤兔马.hourseNum)
6.Try-except
例:
class InShortError(Exception):
def __init__(self, length, least):
self.length = length
self.least = least
try:
s = input("请输入:")
if len(s) <3:
raise InShortError(len(s),3)
except IOError as IO:
print(IO)
except (NameError,InShortError):
print("请输入更多!")
else:
print(“没有问题。")
finally:
print("Close.......................")
7.定义类中的静态方法
class Test(object):
testNum = 0
@staticmethod #区别于类方法@classmethod
def Cacu(): #括号中不添加任何事物
Test.testNum+=1 #直接通过类名调用类属性,与类方法cls.testNum不同,作用相同
return Test.testNum