Python如何把类的一个方法变为属性?

需求:

  • Python如何把类的一个方法变为属性?

解决:

  • 用@property装饰器 (property 财产 [ˈprɒpəti])
  • class obj:
        def __init__(self, host):
            self.host = host    # 属性
    
        @property   # 赋予属性的功能
        def get(self):
            x = 10
            y = 20
            z = self.host
            return x+y+z
    
    res = obj(300)
    print(res.get)

     

  •  

     


     

     

posted @ 2022-12-05 15:35  o蹲蹲o  阅读(199)  评论(0编辑  收藏  举报