How to call variables and methods in another class in one class?
The following code
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 <= 0:
print("[%s]无子弹了" % self.model)
return
else:
self.bullet_count -= 1
print("[%s]突突突...[%d]" % (self.model, self.bullet_count))
class Solder:
def __init__(self, name):
self.name = name
self.gun = Ak47.model # 这个地方可以用外部方法调用另一个类中的变量
def fire(self):
if self.gun is None:
print("[%s]还没有枪" % self.name)
return
print("奥利给,冲啊")
Ak47.add_bullet(50) # 这个用法好
# Gun.add_bullet(50)
Ak47.shoot()
Ak47 = Gun("AK47")
xusanduo = Solder("许三多")
# xusanduo.gun = Ak47
xusanduo.fire()
print(xusanduo.gun)
One class calls the variable of another class with object. variable, and the function of calling another class is self. class name. method name
Private methods and attributes are added before the method or variable,
but there are methods and attributes that are not very private, and the knowledge is relatively private. It can be accessed externally with _class name__method name/variable name,
class Women:
def __init__(self, name):
self.name = name
self.__age = 18
def __secret(self):
print("%s 年龄是 %d" % (self.name, self.__age))
xiaofang = Women("小芳")
xiaofang._Women__secret()
print(xiaofang._Women__age)
But pycharm does not support