Creating an instance when the argument is already an instance.

Hans Mulder hansmu at xs4all.nl
Thu Jul 5 10:43:44 EDT 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
> 		self.asdf=arg
> 
>>>> def package(arg):
> 	if isinstance(arg,_package): return arg
> 	return _package(arg)
> 
>>>> a=package("Test")
>>>> b=package(a)
>>>> a is b
> True
> 
> 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.

Maybe:

class _package:
    def __init__(self, name):
        self.name = name
         # etc.

packages = dict()

def package(name):
    if name not in packages:
        packages[name] = _package(name)
    return packages[name]


Hope this helps,

-- HansM



More information about the Python-list mailing list