层次结构,递归和展平 ¶
我们在第4章结束时( 流(一) )有一个包含在另一个 Streams
对象中的流。让我们重新创建该类:
Stream
到目前为止,找出所包含的流中的内容的唯一方法是使用
from music21 import *
note1 = note.Note("C4")
note1.duration.type = 'half'
note2 = note.Note("F#4")
note3 = note.Note("B-2")
stream1 = stream.Stream()
stream1.id = 'some notes'
stream1.append(note1)
stream1.append(note2)
stream1.append(note3)
biggerStream = stream.Stream()
note2 = note.Note("D#5")
biggerStream.insert(0, note2)
biggerStream.append(stream1)
方法,并使用 show()
参数。
('text')
biggerStream.show('text')
如第4章所述,有一种方法可以访问内部音符,例如
{0.0} <music21.note.Note D#>
{1.0} <music21.stream.Stream some notes>
{0.0} <music21.note.Note C>
{2.0} <music21.note.Note F#>
{3.0} <music21.note.Note B->
通过 F#
格式,但在music21中有更好的方法来做到这一点,为此我们需要了解Stream的子类和一般的子类。(如果您已经从其他编程经验中了解此类知识,请跳过此部分)
类和子类 ¶
一个对象,比如一个音符或音高,基本上是一组信息以及可以对该信息执行的一些操作。类是可以创建特定类型新对象的东西(有时称为工厂)。我们已经看到了一些类,比如 biggerStream[1][1]
类,其中小写的 note.Note
是该类所在的“模块”:
Note
note
<module 'music21.note' from '/Users/cuthbert/music21/note.py'>
print(note.Note)
我们通过在类名后面使用
<class 'music21.note.Note'>
来从类创建对象:
()
n = note.Note()
n
正如我们已经看到的,有时我们可以将其他信息放入
<music21.note.Note C>
中,例如音符的音高名称:
Note
d
在最顶部的位置有一行代码
Help on class Note in module music21.note:
class Note(NotRest)
| One of the most important music21 classes, a Note
| stores a single note (that is, not a rest or an unpitched element)
| that can be represented by one or more notational units -- so
| for instance a C quarter-note and a D# eighth-tied-to-32nd are both
| a single Note object.
|
| *** ............ ***
|
| Method resolution order:
| Note
| NotRest
| GeneralNote
| music21.base.Music21Object
| builtins.object
。 这表示 class Note(NotRest)
类是一个叫做 Note
的类的“子类”,该类包含了所有类似音符的信息,例如 NotRest
、 Note
打击乐器和 Unpitched
,这些都有符杆、梁等,而且不是休止符。(Chris Ariza和我花了一个多小时试图给这些东西想一个更好的名字,但最后我们无法想出比 Chord
更好的名字,所以就这样吧)。
对于 NotRest
是 Note
的子类意味着什么?意味着 NotRest
能做的任何事情, NotRest
也能做,并且更多。例如, Note
有一个 NotRest
属性,所以 .beams
也有:
Note
nr = note.NotRest()
n = note.Note()
print(nr.beams, n.beams)
但是
<music21.beam.Beams> <music21.beam.Beams>
不是 Rest
的子类,这是显而易见的原因。所以一个 休止符不知道任何关于波束的信息:
NotRest
r = note.Rest()
r.beams
但是
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [9], in &l