is it possible to give an instance a value?
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Tue Mar 6 19:12:17 EST 2007
manstey a écrit :
> Hi,
>
> My question probably reflects my misunderstanding of python objects,
> but I would still like to know the answer.
>
> The question is, is it possible for an instnace to have a value (say a
> string, or integer) that can interact with other datatypes and be
> passed as an argument?
In Python, strings and integers *are* objects (instances of resp. str
and int).
> The following code of course gives an error:
>
> class Test(object):
> def __init__(self, val):
> self.val = val
>
>
>>>>a = Test('hello')
>>>>a.val + ' happy'
>
> 'hello happy'
>
>>>>a + 'happy'
>
> TypeError: unsupported operand type(s) for +: 'Test' and 'str'
No surprise so far.
> Is there a way to make a have the value a.val
Forget about the value/instance distinction - it doesn't exists in Python.
> when it is used as
> above,
implement __add__ (and any other appropriate magic method)
> or as an argument (eg function(a, 10, 'sdf') etc)?
>
> The only fudge I discovered for simple addition was to add to the
> class
>
> def __add__(self, obj):
> return a.val + obj
So what's your problem exactly ?
> but this doesn't solve the problem in general. I have tried
> subclassing the string type, but as it is immutable, this is not
> flexible the way a.val is
Err... In your above example implementation, a.val actually *is* a string.
> (i.e. it can't e reassigned
???
a.val = "tutu"
> and remain a
> subclass).
???
> Any pointers, or is my question wrong-headed?
I'm afraid I don't get the point.
> btw, my motivation is wanting to mimic another oo language which
> allows this, so it allows:
>
>>>>Person.Address
>
> 'Sydney'
>
>>>>Person.Address.type
>
> '%String'
>
>>>>Person.Address = 'Canberra'
>>>>print Person.Address. Person.Address.type
>
> Canberra %String
>
> etc.
> We have had to implement Person.Address as Person.Address.val, making
> Address an instance with .val, .type, etc.
>>> class Person(object):
... def __init__(self):
... self.address = "sidney"
...
>>> person = Person()
>>> person.address
'sidney'
>>> type(person.address)
<type 'str'>
>>> # this is equivalent:
>>> person.address.__class__
<type 'str'>
>>> # of if you want the name of the class instead
>>> # of the class object itself:
>>> person.address.__class__.__name__
'str'
>>>
Looks like you'd better learn the Python way instead of wasting your
time trying to mimic some other language (BTW, is it VB or C# ?).
HTH
More information about the Python-list
mailing list