问题描述
我有一个“TrackPage”类,它是一个网页类,其中包含从页面获取的信息,例如跟踪标题、URL 和文件 - 从页面下载的文件。
track 属性本身是一个“Track”类,它应该从调用它的 TrackPage(如标题,但不是 URL)中获取一些属性值,但也有自己的属性,如长度、大小等:>
class TrackPage(BasePage):
def __init__(self):
self.track_title = 'foo'
self.url = 'www.bar.com'
self.file = 'baz.mp3'
self.track = Track()
class Track:
def __init__(self):
self.track_title = # Take TrackPage attribute
self.file = # Take TrackPage attribute
self.length = # Obtained through processing TrackPage attribute file
self.size = # Obtained through processing TrackPage attribute file
从我读到的内容来看,似乎使用包含我想要的 TrackPage 属性的 mixin 类是可行的方法,但我找不到与我想要做的类似的示例。
针对此类场景构建类的最佳方法是什么?
解决方法
您至少有两个选择。
首先是传入 TrackPage
实例并收集你想要的属性:
class TrackPage(BasePage):
def __init__(self):
self.track_title = 'foo'
self.url = 'www.bar.com'
self.file = 'baz.mp3'
self.track = Track(self)
class Track:
def __init__(self,tp):
self.track_title = tp.track_title
self.file = tp.file
self.length = tp.file.length # or however
self.size = tp.file.size # or however
第二种是只保留 TrackPage
实例并在需要时引用该属性:
class TrackPage(BasePage):
def __init__(self):
self.track_title = 'foo'
self.url = 'www.bar.com'
self.file = 'baz.mp3'
self.track = Track(self)
class Track:
def __init__(self,tp):
self.track_page = tp
def get_file(self):
return self.track_page.file