is it possible to give an instance a value?

egbert egbert.bouwman at hccnet.nl
Wed Mar 7 10:02:05 EST 2007


On Tue, 06 Mar 2007 14:45:45 -0800, manstey wrote:
> 
> class Test(object):
>      def __init__(self, val):
>            self.val = val
> 
> a = Test('hello')

> Is there a way to make a have the value a.val when it is used as
> above, or as an argument (eg function(a, 10, 'sdf') etc)?
> 
My impression is that you can do everything you want to
by making your instance callable, and not using a but a().

This is just an example:

class Persoon(object):
    def __init__(self, adres):
        self.adres=adres
        
    def __call__(self, new_adres=None):
        if new_adres: self.adres = new_adres
        return self.adres
    
a = Persoon("Sidney")
print "Living in " + a()
a("Canberra")
print "Living in " + a()
print "Now living in ", a("Amsterdam")
print "Type of a() is: %s" % type(a())
print "Now earning" , a(1234) + 500
print "Type of a() is: %s" % type(a())
print "string ? %s" % ["No","Yes"][isinstance(a(), basestring)]

The output is:

Living in Sidney
Living in Canberra
Now living in  Amsterdam
Type of a() is: <type 'str'>
Now earning 1734
Type of a() is: <type 'int'>
string ? No


e
-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991
========================================================================



More information about the Python-list mailing list