如何在Pyventory中复用自动计算属性?含资产类代码场景
复用App类的hostname属性逻辑到Service类里
看起来你想让Service类复用App类里hostname的格式化逻辑,同时使用Service自身的name和base_domain属性值对吧?这里有几种简洁的实现方式:
方案1:把通用逻辑抽到父类Asset中(推荐)
既然两个类都遵循相同的hostname格式化规则,最合理的方式是把这个逻辑统一放到父类Asset里,所有子类直接继承复用即可:
class Asset: # 将通用的hostname生成逻辑作为属性放到父类 @property def hostname(self): return f"{self.name}.{self.base_domain}" class App(Asset): # 无需重复定义hostname,直接继承父类逻辑 pass class Service(Asset): # 同样复用父类逻辑,自动使用自身的name和base_domain属性 pass
这样不管是App还是Service的实例,调用hostname时都会自动用自身的属性值生成对应的主机名,既避免了代码重复,又保证了逻辑一致性。
方案2:直接复用App类的格式字符串(无法修改父类时用)
如果没办法调整Asset父类的代码,你可以直接引用App类里的格式规则,在Service类中重新实现属性:
class App(Asset): hostname = "{name}.{base_domain}" class Service(Asset): # 复用App的格式模板,绑定自身属性值 @property def hostname(self): return App.hostname.format(name=self.name, base_domain=self.base_domain)
如果你的hostname原本是类属性而非实例属性,也可以把模板单独抽出来方便复用:
class App(Asset): hostname_template = "{name}.{base_domain}" class Service(Asset): # 直接复用App的模板 hostname_template = App.hostname_template @classmethod def get_hostname(cls, name, base_domain): return cls.hostname_template.format(name=name, base_domain=base_domain)
不管用哪种方式,核心都是复用已有的格式规则,同时绑定当前类/实例的属性值,既减少重复代码,也方便后续统一修改规则。
内容的提问来源于stack exchange,提问作者lig
相关产品推荐
相关产品推荐

