The built-in classes of python ‘generate’ objects ‘with a value’. Eg
the integer class has (somehow) generated an object with value 5.
Observation: this ‘value’ is accessible without using the dot-notation.
Objects have state. For an int, that state is the integer value.
But can you access it? What does that mean?
You can do artihmetic with an int. But you can define other classes with
'dotted" internal state and do arithmetic with them, too. The same for
printing and so forth.
Suppose I define a complex number type:
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = image
def __str__(self):
return f"{self.real}+{self.imag}j"
def __add__(self, other):
return Complex(self.real+other.real, self.imag+other.imag)
c = Complex(1, 3)
d = Complex(4, 5)
e = c + d
I can print(c), or add c+d directly. How is this different from an int?
To be sure, you can access the real and imaginary components
individually via the .real and .imag attributes, but in other respects
this looks like any other value.
Can you elaborate on how this isn’t like an int (in the sense you’re
getting at in this message)?
I wonder if we can replicate this behaviour for other, self written,
classes.
I’m working on a simulation where sometimes variables need to be fixed (hence built-ins like int’s) and sometimes some variables should be stochastic (hence ‘returning’ a different value each time it is accessed). I don’t want to change the code of the simulation.
This normally amounts to providing the same methods on both types of
things.
Can you give an example of your attempt at each of these and a tiny
piece of simulation code you wish to work identically for both?
Cheers,
Cameron Simpson cs@cskk.id.au