I have a number of objects of the same class, each holding different data.
However, they have a number of attributes that should be 'common' - i.e. set to the same value across all objects. (this could be a numeric value, a reference to another object etc etc)
What are different methods of implementing this? A couple of methods I thought of:
A dictionary containing all the objects and the common attributes as separate key/value pairs. The problem here is that the objects are dynamically created (there is a variable number of objects read from file) so creating keys could be a problem
A 'collection' class, where the common attributes are defined in this collection class and the group of objects is passed in as a list
I can't help feeling that there might be alternatives out there, or 'better' methods (I know that is subjective, but I'd like to know all possibilities...)
Edit:.
Here is my specific example.
I have a number of objects, each defining the branch of a river (from now on called Branches. So, they all have different x,y point attributes.
They should all be 'linked' to another object, in this case an object describing the elevation over the domain (from now on called DEM)
One way to do it could be a 'collector' class (call it Network) which groups together all the Branches objects and has an attribute which is a reference to the DEM.
This way, I can safely use the DEM in all calculations using Branches. However, it is not ideal. I would like each Branches object to have a method which returns the elevation at each point. For that, DEM needs to either be passed into the Branches method (meaning I cannot define that method as a property, which I would like to do) or there needs to be an attribute within each Branches object pointing to DEM. The second method runs the risk of allowing separate instances of DEM to be referenced within each Branches object, which I don't won't to allow. It also seems a bit silly to have each Branches object holding a separate reference to the same thing (1 global reference would be preferred - this way I can change it without having to go through each Branches object).
I find this kind of thing cropping up all over - I have a load of instances of the same object, but I want to keep some attributes common between them - so more general answers are preferred..
If you want to have attributes that are shared by and accessible to all instances of a class, use class attributes:
class MyClass(object):
myclassattr = 0 # class attribute
def __init__(self, attr):
self.myinstattr = attr # instance attribute
if MyClass.myclassattr == 0:
print("First!")
MyClass.myclassattr += 1
For example:
>>> a = MyClass()
First!
>>> b = MyClass()
>>> MyClass.myclassattr
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With