类命名空间与对象、实例的命名空间

创建一个类就会创建一个类的名称空间,用来存储类中定义的所有名字,这些名字称为类的属性

而类有两种属性:静态属性和动态属性

  • 静态属性就是直接在类中定义的变量
  • 动态属性就是定义在类中的方法

 

一、静态属性

class Person:
    money = 0


mother = Person()
father = Person()
mother.money += 1000
father.money += 1000
# 0
print(Person.money)

# 静态成员变量属于类,不属于对象
Person.money += 1000
Person.money += 1000
# 2000
print(Person.money)
# 创建一个类,每个实例化一个对象计数
# 最终所有的对象共享这个数据

class Foo:
    count = 0

    def __init__(self):
        # 注意使用类名,不使用self.count,self是当前对象
        # self.count+=1
        Foo.count += 1


a = Foo()
print(Foo.count)
b = Foo()
print(Foo.count)

 

面向对象的组合用法

软件重用的重要方式除了继承之外还有另外一种方式,即:组合

组合指的是,在一个类中以另外一个类的对象作为数据属性,称为类的组合

class Dog:
    def __init__(self, name, aggr, hp, kind):
        self.name = name
        self.aggr = aggr
        self.hp = hp
        self.kind = kind

    def bite(self, person):
        person.hp -= self.aggr


class Person:
    def __init__(self, name, aggr, hp, sex):
        self.name = name
        self.aggr = aggr
        self.hp = hp
        self.sex = sex
        self.money = 0

    def attack(self, dog):
        dog.hp -= self.aggr

    # weapon是Weaon类的对象
    def get_weapon(self, weapon):
        if self.money >= weapon.price:
            self.money -= weapon.price
            # 一个对象的属性值是另外一个类的对象
            #        alex.weapon 是 Weapon类的对象
            self.weapon = weapon
            self.aggr += weapon.aggr
        else:
            print("余额不足,请先充值")


class Weapon:
    def __init__(self, name, aggr, njd, price):
        self.name = name
        self.aggr = aggr
        self.njd = njd
        self.price = price

    def hand18(self, person):
        if self.njd > 0:
            person.hp -= self.aggr * 2
            self.njd -= 1


alex = Person('alex', 0.5, 100, '不详')
jin = Dog('金老板', 100, 500, 'teddy')
w = Weapon('打狗棒', 100, 3, 998)
# alex装备打狗棒
alex.money += 1000
alex.get_weapon(w)
print(alex.weapon)
print(alex.aggr)
alex.attack(jin)
print(jin.hp)
alex.weapon.hand18(jin)
print(jin.hp)