Getting attributes from a list containing classes - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Getting attributes from a list containing classes (/thread-22895.html) |
Getting attributes from a list containing classes - midarq - Dec-02-2019 Hi! I have a small problem: I defined a class Tone which inherits from the class Recorder. (i.e. a recorder is an instrument which has many notes). Each Tone has certain attributes like frequency, fingering, etc. Currently, I am doing the following: class Recorder(object): def __init__(self): self.alltones=[Tone(ii) for ii in range(10)] class Tone(Recorder): def __init__(self,ii): self.frequency=2**(ii/12) This however doesn't satisfy me as I would like to be able to easily create a list of all frequencies from an instance of Recorder. Something along these lines a=Recorder() a.alltones.frequencyIn particular, I am looking for a clean way of creating lists of the following type [Tone(ii).attribute for ii in range(10)]Thank you in advance for your help :) RE: Getting attributes from a list containing classes - Clunk_Head - Dec-02-2019 You have a fundamental misunderstanding of inheritance. Inheritance is base on the is-a relationship. What you have is the has-a relationship. The is-a relationship is easily demonstrated using vehicles: Car is-a Ground_Vehicle is-a Vehicle Truck is-a Ground_Vehicle is-a Vehicle Hang_Glider is-a Flying_Vehicle is-a Vehicle Biplane is-a Flying_Vehicle is-a Vehicle These relationships can be expressed as a tree So we would create: class Vehicle class Ground_Vehicle(Vehicle) class Car(Ground_Vehicle) class Truck(Ground_Vehicle) class Flying_Vehicle(Vehicle) class Hang_Glider(Flying_Vehicle) class Biplane(Flying_Vehicle)This allows us to express the is-a relationship and inherit the properties of the parent class(es) as we go. You have a has-a relationship. A recorder has-a tone, or in this case a list of tones. To handle this relationship you need to make class Tone and class Recorder and in the init of recorder give it a list of Tones: class Recorder: def __init__(self, tones): self.alltones = tones bass_recorder = Recorder([Tone('Gs'), Tone(Af), Tone(An), Tone(As), . . .]) #then you can access all of the tones in any given recorder as a property of that recorder print(bass_recorder.alltones)Since a Tone is not a recorder you just create class Tone with its own properties, such as note name and frequency. RE: Getting attributes from a list containing classes - midarq - Dec-03-2019 Fantastic explanation, thank you! |