Creating an instance when the argument is already an instance.
hansmu at xs4all.nl
Thu Jul 5 16:43:44 CEST 2012
On 5/07/12 12:47:52, Chris Angelico wrote:
> On Thu, Jul 5, 2012 at 8:29 PM, Olive <diolu at bigfoot.com> wrote:
>> I am creating a new class: package (to analyse the packages database in
>> some linux distros). I have created a class package such that
>> package("string") give me an instance of package if string is a correct
>> representation of a package. I would like that if pack is already an
>> instance of package then package(pack) just return pack.
> One way would be to make the name "package" actually a wrapper
> function, not the class itself:
>>>> class _package:
> def __init__(self,arg):
> # blah blah
>>>> def package(arg):
> if isinstance(arg,_package): return arg
> return _package(arg)
>>>> a is b
> The leading underscore is a common convention meaning "private
> implementation detail".
I think using a factory function is the right idea, but the
code above doesn't solve the problem as stated. Olive needs
a factory function that takes a string argument and returns
a _package object.
def __init__(self, name):
self.name = name
packages = dict()
if name not in packages:
packages[name] = _package(name)
Hope this helps,
More information about the Python-list