我想创建一个对象来表示一些电子读数,例如输入电压。为此,我想创建一个基本的类结构来处理不同类型的读数——比如电流和电压。
我想做的伪代码(实际上是Python)是这样的:
# Create base class as a subclass of a common class to all other classes
class PowerReading(object):
# Defining word to initialize instance variables using the given input
def __init__(self, current_value, units):
# instance variables
self.value = current_value
self.units = units
# Define new class based on our generic class above
class Voltage(PowerReading):
# Call the parent class word with an input value, and constant units string
def __init__(self, current_value):
super(Voltage, self).__init__(current_value, 'volts')
# Create another class based on the same parent class as Voltage
class Current(PowerReading):
def __init__(self, current_value):
# Call the parent word with current units
super(Voltage, self).__init__(current_value, 'amps')
# input_voltage_atod() is defined elsewhere: gives an instant reading
# from the ATOD pin on the power input rail, already converted to units of volts.
# Create instance object variable using our new Voltage class.
input_voltage = Voltage(input_voltage_atod())
# Use the object's instance variables
print input_voltage.value, input_voltage.units
# 3.25 volts
我使用Gforth
和oof.fs
扩展。
用一些简单的gforth符号:
: symbol ( "name" -- )
create lastxt , does> ( -- xt ) @ ;
: .symbol ( xt -- )
>name name>string 1 /string type ;
symbol 'volts
symbol 'amps
这里有一个厕所。
require oof.fs
object class power-reading
float var value
cell var units
method .
how:
: init ( r-value units -- ) units ! value f! ;
: . ( -- ) value f@ f. units @ .symbol space ;
class;
power-reading class voltage
how:
: init ( r-value -- ) 'volts super init ;
class;
power-reading class current
how:
: init ( r-value -- ) 'amps super init ;
class;
3.25e voltage : input-voltage
input-voltage . Output: 3.25 volts
这很相似,不是吗?
这些天我用mini-oof2。Fs,比Fs低得多,它的作用要小得多。在:
object class
ffield: value
field: units
method init ( value units -- )
method show ( -- )
end-class power-reading
[: ( r-value units -- ) units ! value f! ;] power-reading to init
[: ( -- ) value f@ f. units @ .symbol space ;] power-reading to show
power-reading class
end-class voltage
[: ( r-value -- ) value f! 'volts units ! ;] voltage to init
power-reading class
end-class current
[: ( r-value -- ) value f! 'amps units ! ;] current to init
voltage new constant input-voltage
3.25e input-voltage .init
input-voltage .show Output: 3.25 volts
[: ... ;]
不是特殊的mini-oof2。fs语法。他们只是
.init
和.show
宏观扩展到>o init o>
和>o show o>
.
比起使用INIT方法,我经常使用一个非oo单词构造对象:
: >current ( r -- o )
current new >o value f! 'amps units ! o o> ;
: current, ( r -- )
here >o [ current >osize @ ]L allot value f! 'amps units ! o> ;
当然,这在复杂的面向对象中并不适用以及SUPER方法等等。它是90%的溶液而不是100%的由oof提供的OO解决方案。