1 回答

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
子path屬性會(huì)覆蓋base.path。您不覆蓋的是url屬性。當(dāng)運(yùn)行 的主體base來(lái)創(chuàng)建類對(duì)象時(shí),就會(huì)計(jì)算一次。
未來(lái)你有幾個(gè)選擇。無(wú)論哪種方式,您都需要url動(dòng)態(tài)地進(jìn)行計(jì)算,或者每次訪問(wèn)它時(shí),或者每個(gè)子類至少一次。
最簡(jiǎn)單的方法是制作url成classmethod:
class base:
host = "/host/"
path = "Override this in child classes"
@classmethod
def url(cls):
return urljoin(cls.host, cls.path)
@classmethod
def print_url(cls):
print(cls.url())
class config(base):
path = "config"
class log(base):
path = "log"
請(qǐng)注意,您現(xiàn)在指的是實(shí)際的類host并且path是動(dòng)態(tài)的。您還只需要一種print_url方法,base而不是每個(gè)類中使用不同的方法。
base另一種選擇是為 及其所有子級(jí)提供一個(gè)元類,url其形式為property:
class url_meta(type):
@property
def url(cls):
return urljoin(cls.host, cls.path)
class base(metaclass=url_meta):
host = "/host/"
path = "Override this in child classes"
@classmethod
def print_url(cls):
print(cls.url)
class config(base):
path = "config"
class log(base):
path = "log"
這是可行的,因?yàn)?python 類也是對(duì)象。property您可以在類的類(元類)中定義 a ,它的行為與任何property對(duì)實(shí)例的行為一樣。這次實(shí)例本身就是一個(gè)類。
第三種選擇是確保url在每個(gè)子項(xiàng)中靜態(tài)但正確地定義它。該__init_subclass__方法允許您直接從以下位置非常方便地執(zhí)行此操作base:
class base:
host = "/host/"
path = "Override this in child classes"
url = urljoin(host, path)
@classmethod
def __init_subclass__(cls):
cls.url = urljoin(cls.host, cls.path)
@classmethod
def print_url(cls):
print(cls.url)
class config(base):
path = "config"
class log(base):
path = "log"
您也可以使用元類完成同樣的事情:
class url_meta2(type):
def __init__(cls, *args, **kwargs):
cls.url = urljoin(cls.host, cls.path)
class base(metaclass=url_meta2):
host = "/host/"
path = "Override this in child classes"
@classmethod
def print_url(cls):
print(cls.url)
class config(base):
path = "config"
class log(base):
path = "log"
添加回答
舉報(bào)