Class property with value and class

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Dec 19 18:02:04 EST 2006


"manstey" <manstey at csu.edu.au> writes:

> Is is possible to have two classes, ClassA and ClassB, and
> setattr(ClassA, 'xx',ClassB), AND to then have ClassA.xx store an
> integer value as well, which is not part of ClassB?

You seem somewhat confused over classes and instances. There's little
need to externally set an attribute on a class; you'd be much more
likely to *inherit from* that class and override some attributes.

> e.g. If ClassB has two properties, name and address:
>
> ClassA.xx=10

This syntax (the raw text "10") will only ever create an object of
type 'int'. Since 'int' objects don't have the 'name' and 'address'
attributes, and can't gain them, your next two lines will fail with
AttributeError.

> ClassA.xx.name = 'John'
> ClassA.xx.address = 'Sydney'.

So, you can define a class that does have this behaviour, but you'll
have to explicitly create instances of it::

    foo.bar = WeirdClass(10)
    foo.bar.name = "John"
    foo.bar.address = "Sydney"

> etc?  I've no idea if this is possible or desirable.

I, too, wonder why on earth you'd want to do this, rather than having
the value 10 assigned to a named attribute.

-- 
 \        "If you go to a costume party at your boss's house, wouldn't |
  `\     you think a good costume would be to dress up like the boss's |
_o__)                       wife? Trust me, it's not."  -- Jack Handey |
Ben Finney




More information about the Python-list mailing list