class HomeItem :
def __init__(self, name, area):
self.name = name
self.area = area
def __str__(self):
return "%s 的面积是%s"% (self.name, self.area)
class house :
def __init__(self, house_type, area):
self.house_type = house_type
self.area = area
self.free_area = area
self.item_list = []
def __str__(self ):
return ("%s 的总面积是 %s,有%s 家具"
%(self.house_type,self.area,self.item_list))
def add_item(self, item):
print("添加家具 %s" % item.name)
if item.area > self.free_area :
print("%s 太大,放不下了" % item.name)
return
self.item_list.append(item.name)
self.free_area -= item.area
print("剩余面积为: %s"%self.free_area)
bed = HomeItem("床", 4)
print(bed)
my_home = house("大屋", 80)
my_home.add_item(bed)
print(my_home)
class Soldier:
def __init__(self, name):
self.name = name
self.gun = None
def fire(self):
if self.gun is None:
#if use "self.gun == None" ,it means the content equls ,but "is" means those point to the one thing ,no the content
print("[%s]还没发枪" % self.name)
return
print("[%s]终于拿到枪了,给他弹夹就可以上战场了" % self.name)
self.gun.add_bullet(50)
print("[%s]的" % self.name, end="")
self.gun.shoot()
class Gun:
def __init__(self, model):
self.model = model
self.bullet_count = 0
def add_bullet(self, count):
self.bullet_count += count
def shoot(self):
if self.bullet_count:
self.bullet_count -= 1
print("[%s]突突突...剩余子弹[%d]" % (self.model, self.bullet_count))
else:
print("[%s]没有子弹了" % self.name)
ak = Gun("AK47")
# ak.add_bullet(50)
# ak.shoot()
xs = Soldier("士兵")
xs.gun = ak
print(xs.gun)
xs.fire()
private parament and private function
key char :
__para ,__functionname()
it just excute in the function,can be excute through the object's parament
class Women:
def __init(self, name):
self.name = name
self.__age =18
def secret(self):
print("the age is %d"%self.__age)
def __secret(self):
print("the age is %d"%self.__age)
xf = Women("xiaofang")
print(xf.__age)
#it can no work
xf.secret()
xf.__secret()
#it can not works
if we want to excute the private paramen,we can use this method.it is no advied to do
print(xs._Women__age)
#it can works
xf._Women__secret())
#it can works
inheritance
override
polymorphic
class Animal:
def eat(self):
print("eat!!!")
def drink(self):
print("drink!!!")
def sleep(self):
print("sleeping!!!")
def run(self):
print("run!!!!")
class Dog(Animal):
#single inheritance
def bark(self):
print("barking!!!")
def eat(self):
print("the Dog is eatting!!!")
#function override
def sleep(self):
#expand override
print("sleeping!!!-----")
super().sleep()
#Animal.sleep(self)#this can works in version python 2.x
print("---------")
class XTQ(Dog):
#multiple inheritance
def fly(self):
print("flying!!!")
k = Dog()
f = XTQ()
k.eat()
f.fly()