如何在不使用任一类的对象实例的情况下覆盖子类中的父类属性?来自 Java/C++ 及其严格结构设计的世界,我发现自己受到 Python 做事方式的挑战。我想保持相对静止。
例子:
from urllib.parse import urljoin
class base:
host = "/host/"
path = "Override this in child classes"
url = urljoin(host, path)
class config(base):
path = "config"
@classmethod
def print_url(cls):
print(cls.url) # Currently prints "/host/Override this in child classes"
# Would like to print "/host/config" instead
class log(base):
path = "log"
@classmethod
def print_url(cls):
print(cls.url) # Currently prints "/host/Override this in child classes"
# Would like to print "/host/log" instead
所需用途:
>>> config.print_url()
/host/config
>>> log.print_url()
/host/log
我希望config.path和log.path属性能够覆盖base.path. 这样我就可以url = urljoin(host, path)在类中一劳永逸地使用base(并且避免必须在每个派生类中复制/粘贴相同的属性/计算)。
我无法弄清楚如何在不构造对象的情况下完成此任务(我希望避免)。有人有什么建议吗?提前致谢!
守着一只汪
相关分类