1 析构方法
class Animal:
def __init__(self,name):
self.name=name
print ('这是构造初始化方法')
pass
def __del__(self):
print ('当在某个作用域下,没有被使用的情况下,解析器就会自动调用此函数,释放内存空间')
print ('这是析构方法')
print('%s对象被彻底清理,内存空间也释放'%self.name)
pass
cat=Animal('小花猫')
del cat
input('程序等待中*********')
2 单继承
class Animal:
def eat(self):
print ('吃饭了')
pass
def drink(self):
pass
class Dog(Animal):
def wwj(self):
print ('汪汪叫')
pass
class Cat(Animal):
def mmj(self):
"""
子类独有的实现
:return:
"""
print('喵喵叫')
pass
d1=Dog()
d1.eat()
c1=Cat()
c1.eat()
c1.mmj()
3 多继承
class shenxian:
def fly(self):
print("神仙都会飞")
pass
class Monkey:
def chitao(self):
print('猴子喜欢吃桃')
pass
class Sunwukong(shenxian,Monkey):
pass
swk=Sunwukong()
swk.chitao()
swk.fly()
class D(object):
def eat(self):
print('D.eat')
pass
pass
class C(D):
def eat(self):
print('C.eat')
pass
pass
class B(D):
pass
class A(B,C):
pass
a=A()
a.eat()
print(A.__mro__)
class GrandFather:
def eat(self):
print('吃的 方法')
pass
pass
class Father(GrandFather):
def eat(self):
print('爸爸经常吃海鲜')
pass
class Son(Father):
pass
son=Son()
son.eat()
4 重写及调用父类
class Dog:
def __init__(self,name,color):
self.name=name
self.color=color
def bark(self):
print('汪汪叫....')
pass
pass
class kejiquan(Dog):
def __init__(self,name,color):
super().__init__(name,color)
self.height=90
self.weight=20
pass
def __str__(self):
return '{}的颜色会{} 它的身高是{}cm 体重是:{}'.format(self.name,self.color,self.height,self.weight
)
def bark(self):
super().bark()
print('叫的跟神一样')
print(self.name)
pass
kj=kejiquan('柯基犬','红色')
kj.bark()
print(kj)
5 多态
class Animal:
"""
父类【基类】
"""
def say_who(self):
print('我是一个动物......')
pass
pass
class Duck(Animal):
"""
鸭子类【子类】派生类
"""
def say_who(self):
"""
在这里重写父类的方法
:return:
"""
print('我是一只漂亮的鸭子')
pass
pass
class Dog(Animal):
"""
小狗类【子类】派生类
"""
def say_who(self):
print('我是一只哈巴狗')
pass
pass
def commonInvoke(obj):
"""
统一调用的方法
:param obj: 对象的实例
:return:
"""
obj.say_who()
listobj=[Duck(),Dog()]
for item in listobj:
commonInvoke(item)
6 类属性和实例属性
class Student:
name='李明'
def __init__(self,age):
self.age=age
pass
pass
Student.name='小花'
lm=Student(18)
print(lm.name)
print(lm.age)
print("----------------------通过类对象student访问name————————")
print(Student.name)
xh=Student(28)
xh.name='小溪'
print(xh.name)
xh.name='小花'
print(xh.age)
7类方法和静态方法
class People:
country='China'
@classmethod
def get_country(cls):
return cls.country
pass
@classmethod
def change_country(cls,data):
cls.country=data
pass
@staticmethod
def getData():
return People.country
pass
@staticmethod
def add(x,y):
return (x+y)
pass
print(People.add(10,56))
print(People.getData())
import time
class TimeTest:
def __init__(self,hour,min,second):
self.hour=hour
self.min=min
self.second=second
@staticmethod
def showTime():
return time.strftime("%H:%M:%S",time.localtime())
pass
pass
print(TimeTest.showTime())
|