Object orientation
An introduction to defining and using a TinyChain class
One of TinyChain’s most powerful features is its object-oriented API. You can use this to define your own classes, which must inherit from exactly one class, which ultimately inherits from a native class. For example:
1
from __future__ import annotations # needed until Python 3.10
2
3
LINK = "http://example.com/app/area" # <-- edit this
4
5
# Specifying `metaclass=tc.Meta` provides JSON encoding functionality for user-defined classes.
6
# It's only required when subclassing a native class--subclasses of `Distance` automatically inherit its metaclass.
7
class Distance(tc.Number, metaclass=tc.Meta):
8
__uri__ = tc.URI(LINK) + "/Distance"
9
10
@tc.get_method
11
def to_feet(self) -> Feet:
12
return tc.error.NotImplemented("abstract")
13
14
@tc.get_method
15
def to_meters(self) -> Meters:
16
return tc.error.NotImplemented("abstract")
17
18
class Feet(Distance):
19
__uri__ = tc.URI(LINK) + "/Feet"
20
21
@tc.get_method
22
def to_feet(self) -> Feet:
23
return self
24
25
@tc.get_method
26
def to_meters(self) -> Meters:
27
return self / 3.28
28
29
class Meters(Distance):
30
__uri__ = tc.URI(LINK) + "/Meters"
31
32
@tc.get_method
33
def to_feet(self) -> Feet:
34
return self * 3.28
35
36
@tc.get_method
37
def to_meters(self) -> Meters:
38
return self
Copied!
Note that TinyChain does not have any concept of member visibility, like a “public” or “private” method. This is because TinyChain objects are meant to be sent over the network and used by client code, making a “private” method meaningless (and deceptive to the developer implementing it). If you want to hide an implementation detail from the public API of your class, consider using a helper function outside your class definition.
Copy link