Class property with value and class

M

manstey

Hi,

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?

e.g. If ClassB has two properties, name and address:

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

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

thanks,
matthew
 
D

Diez B. Roggisch

manstey said:
Hi,

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?

e.g. If ClassB has two properties, name and address:

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

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

It's neither of both options. If you must, you can subclass int, and have
additional properties. But then you can't do it like above, but instead
must do:

ClassA.xx = MyAddressInt(10)


Diez
 
B

Ben Finney

manstey said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top