一、面向对象基本理论
1.何为对象?:万物皆为对象(指某一个具体物体,有对应的属性和行为。把很多零散的东西封装成一个整体。)
2.类:什么是类:某一个具体对象特征的抽象,如人类(对象)中的男人女人,张三,李四等(类)。类的作用:根据抽象的类,生产具体的对象。类的组成:名称,属性,,方法等。
二、创建类实例
class Employee:
'所有员工的基类'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
empCount 变量是一个类变量,它的值将在这个类的所有实例之间共享。你可以在内部类或外部类使用 Employee.empCount 访问。
第一种方法__init__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法
self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。
三、多继承
Father.py
class Father(object) :
def _init___(self, money) :
self.money = moneydef play(self):
print("play")def func(self):
print(" func")
Mother.py
class Mother (object):
def __init__(self, faceValue) :
self.faceValue = faceValuedef eat (self):
print("eat")def func(self):
print("func2")
Child.py
from Father import Father
from Mother import Mother
class Child(Father, Mother):#继承两个父类
def __init__(self,money,faceValue)
Father. __init__(self,money)
Mother. __init__(self,faceValue)
主函数中的实现
def main():
c = Child(300,100)
print(c.money,c.faceValue)
c.play()
c.eat()
#注意:父类中方法名相同,默认调用的是在括号中排前面的父类中的方法
c.func()
if _name_= "__main__" :
main()
四、多态
多态:一种事物的多种形态
定义一个有name届性和eat方法的Animal类,让所有的动物类都继承自Animal;再定义一个人去喂这些动物
animal.py
class Animal(object):
def __init__(self,name) :
self.name = name
def eat(self):
print (self.name +"吃")
cat.py
from animal import Animal
class Cat(Animal):
def _init__(self,name):
super (Cat,self).___init__(name)
mouse.py
from animal import Animal
class Mouse(Animal):
def __init__(self,name):
super(Mouse,self).__init__(name)
person.py
class Person(object) :
def feedCat(self, cat):
print("给你食物")
cat.eat()
def feedMouse(self,mouse):
print("给你食物")
mouse.eat()
主函数:
from cat import Cat
from mouse import Mouse
from person import Person
#先调用类
tom = Cat("tom")
jerry = Mouse(" jerry")
per =Person ()
per.feedCat (tom)
per. feedMouse(jerry)
五、对象属性与类属性
class Person (object) :
#这里的属性实际上属于类属性(用类名来调用)
name= "person"
def__init__(self,name) :
#对象属性
self.name = name
print (Person.name)
per = Person("tom")
#对象属性的优先级高于类属性
print(per. name)
#动态的给对象添加对象属性
per. age = 18#只针对于当前对象生效,对于类创建的其他对象没有作用
print(Person. name)
per2= Person("lilei")
#print(per2.age)#没有age属性
注意:以后千万不要讲对象属性与类属性重名,因为对象属性会屏蔽草类属性。但是当删除对象属性后,在使用又能使用类属性了。