Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Getting attributes from a list containing classes
#1
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.frequency
In 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 :)
Quote
#2
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
İmage


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.
Quote
#3
Fantastic explanation, thank you!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  how to add class instance attributes from list 999masks 2 385 Jul-22-2019, 07:59 AM
Last Post: 999masks
  Copying classes in a list marienbad 1 762 Oct-14-2018, 04:42 PM
Last Post: ichabod801
  Classes: How to Print Specific Attributes emerger 3 780 Oct-13-2018, 08:49 PM
Last Post: emerger
  Using classes? Can I just use classes to structure code? muteboy 5 1,768 Nov-01-2017, 04:20 PM
Last Post: metulburr

Forum Jump:


Users browsing this thread: 1 Guest(s)