不明确面向对象的同学,请先阅读面向对象总结:https://blog.csdn.net/zhouzongxin94/article/details/109240059?spm=1001.2014.3001.5501
前置:封装分三种
数据封装、行为封装、思维封装
下述三种实例:
1、类调用基础
# A类调用B类
class A(object):
def run(self, a):
a.run1()
print("A类")
class B(object):
def run1(self):
print("B类")
if __name__ == '__main__':
a1 = A()
b1 = B()
a1.run(b1)
2、A类调用B类调用,含数据
# A类攻击B类调用,含数据
class A(object):
def __init__(self, stk):
self.stk = stk
def run(self, a):
print("A类攻击B类")
a.stk(self.stk)
class B(object):
def __init__(self, hp):
self.hp = hp
def stk(self, value):
print("B类受伤了")
self.hp -= value
print("B类扣除血量%d,剩余血量%d" % (value, self.hp))
if __name__ == '__main__':
a1 = A(10)
b1 = B(100)
a1.run(b1)
3、A类与B类互相调用,含数据
# A类与B类互相调用,含数据
class A(object):
def __init__(self, hp, stk):
self.hp = hp
self.stk = stk
def run(self, a):
print("A类攻击B类")
a.stk1(self.stk)
def stk1(self, value):
print("A类受伤了")
self.hp -= value
print("A类扣除血量%d,剩余血量%d" % (value, self.hp))
class B(object):
def __init__(self, hp, stk):
self.hp = hp
self.stk = stk
def run(self, b):
print("B类攻击A类")
b.stk1(self.stk)
def stk1(self, value):
print("B类受伤了")
self.hp -= value
print("B类扣除血量%d,剩余血量%d" % (value, self.hp))
if __name__ == '__main__':
a1 = A(500, 10)
b1 = B(500, 100)
a1.run(b1)
b1.run(a1)