Change the way an Object is printed: Difference between revisions
Jump to navigation
Jump to search
(imported material) |
No edit summary |
||
| Line 1: | Line 1: | ||
'''Problem'''. Suppose you defined a Class, say '''User''', and suppose this class contains the instance variables <code>name</code>, <code>id</code>, <code>password</code>. When you create a new User object, it will print itself as <code>aUser</code>. This might be ok, but suppose it is usefull for you to always see <code>id</code>. What to do? |
'''Problem'''. Suppose you defined a Class, say '''User''', and suppose this class contains the instance variables <code>name</code>, <code>id</code>, <code>password</code>. When you create a new User object, it will print itself as <code>aUser</code>. This might be ok, but suppose it is usefull for you to always see <code>id</code>. What to do? |
||
'''Solution'''. In the User object define the method <code>printOn:</code>. Watch how it is defined on the class <code>Object</code> and change it a bit, for example as: |
'''Solution'''. In the User object define the method <code>printOn:</code>. Watch how it is defined on the class <code>Object</code> and change it a bit, for example as:<syntaxhighlight lang="smalltalk"> |
||
printOn: aStream |
|||
|str| |
|||
str := ((self class name withArticle) , '-', self id asString). |
|||
aStream nextPutAll: str. |
|||
Cy. Defect: The method above is a bit Pythonic. |
</syntaxhighlight>Cy. Defect: The method above is a bit Pythonic. |
||
This method definition is more Smalltalkish: |
This method definition is more Smalltalkish:<syntaxhighlight lang="smalltalk"> |
||
printOn: aStream |
|||
aStream nextPutAll: self class name; |
|||
nextPut: $-; |
|||
nextPutAll: self id asString . |
|||
| ⚫ | |||
nextPutAll: self id asString |
|||
| ⚫ | |||
----NM 10-Aug-2021. Tested Cuis5.0-4738.image |
----NM 10-Aug-2021. Tested Cuis5.0-4738.image |
||
Latest revision as of 23:09, 4 May 2025
Problem. Suppose you defined a Class, say User, and suppose this class contains the instance variables name, id, password. When you create a new User object, it will print itself as aUser. This might be ok, but suppose it is usefull for you to always see id. What to do?
Solution. In the User object define the method printOn:. Watch how it is defined on the class Object and change it a bit, for example as:
printOn: aStream
|str|
str := ((self class name withArticle) , '-', self id asString).
aStream nextPutAll: str.
Cy. Defect: The method above is a bit Pythonic. This method definition is more Smalltalkish:
printOn: aStream
aStream nextPutAll: self class name;
nextPut: $-;
nextPutAll: self id asString .
Voila, now if you print a user you will see something like aUser-2132. This very practical when you are listing several user objects, for the example in the inspector.
NM 10-Aug-2021. Tested Cuis5.0-4738.image