面向对象 静态方法和动态方法 ;静态更先进因为新建和被调用时不需要传self
展示动态方法 需要加self
# A.py 调用B的制作伞 和扇子 from B import Handmade class Weather: def __init__(self, type): self.type = type def action(self): f = Handmade.make_fan(self) u = Handmade.make_umbrella(self) print("----") if self.type == "sunny": print("晴天") print(f"拿{f}来扇风") elif self.type == "rainy": print("雨天") print(f"拿{u}来挡雨") if __name__ == "__main__": weather = Weather("sunny") weather.action() print("另一种天气----") weather = Weather("rainy") weather.action()
# B.py 制作伞 制作扇子 class Handmade: def make_umbrella(self): print("制作雨伞,以备下雨天用") umbrella="一把雨伞" return umbrella def make_fan(self): print("制作扇子,以备晴天用") fan="一把扇子" return fan if __name__ == "__main__": # 实例化出一个手工对象 handmade = Handmade() # 调用方法1 handmade.make_umbrella() # 调用方法2 handmade.make_fan()
动态方法
第一步 修改B.py为动态方法 加修饰器 去掉self 参数
# B.py 制作伞 制作扇子 class Handmade: @staticmethod def make_umbrella(): print("制作雨伞,以备下雨天用") umbrella="一把雨伞" return umbrella def make_fan(): print("制作扇子,以备晴天用") fan="一把扇子" return fan if __name__ == "__main__": # 实例化出一个手工对象 handmade = Handmade() # 调用方法1 handmade.make_umbrella() # 调用方法2 handmade.make_fan()
第二步 修改A.py 去掉self
# A.py 调用B的制作伞 from B import Handmade class Weather: def __init__(self, type): self.type = type def action(self): f = Handmade.make_fan() u = Handmade.make_umbrella() print("----") if self.type == "sunny": print("晴天") print(f"拿{f}来扇风") elif self.type == "rainy": print("雨天") print(f"拿{u}来挡雨") if __name__ == "__main__": weather = Weather("sunny") weather.action() print("另一种天气----") weather = Weather("rainy") weather.action()