[Tutor] Store Class in Tuple Before Defining it ...
Lie Ryan
lie.1296 at gmail.com
Sat Aug 29 14:05:39 CEST 2009
Damon Timm wrote:
> Sorry for the double post! Went off by mistake before I was done ...
>
> Anyhow, I would like to have a tuple defined at the beginning of my
> code that includes classes *before* they are defined ... as such (this
> is on-the-fly-hack-code just for demonstrating my question):
>
What you want to do can be done with a helper function (e.g.
Sync.find_sync() below), but I smelled a bad class design. Anyway, here
is how you would do it...
class Video(object):
url = '...'
def sync(self):
sync = Sync.find_sync(self.url)
class Sync(object):
class NoSuitableSync(Exception): pass
@staticmethod
def find_sync(url):
for S in Sync.__subclasses__():
if S.RE.match(url):
return S(url)
raise Sync.NoSuitableSync()
class SyncYoutube(Sync):
RE = re.compile(r'some regex here')
class SyncBlip(Sync):
RE = re.compile(r'other regex here')
what I suggest you could do:
class Video(object):
# Video is a mixin class
def __init__(self, url):
self.url = url
def sync(self):
# source agnostic sync-ing or just undefined
pass
@staticmethod
def find_video(url):
for sc in Video.__subclasses__():
if sc.RE.match(url)
return sc(url)
class Youtube(Video):
RE = re.compile('... some regex here ...')
def sync(self):
# costum sync-ing
pass
class Blip(Video):
RE = re.compile('... other regex here ...')
def sync(self):
# costum sync-ing
pass
a = Video.find_video('http://www.youtube.com/xxxx')
that way, url detection will only happen on class initialization instead
of every time sync is called.
More information about the Tutor
mailing list