Ball2.py
print(Ball2) -- <class '__main__.Ball2'>
print(theBall) -- <__main__.Ball2 object at 0x02BD9570>
Ball.py
print(Ball) -- <class '__main__.Ball'>
print(theBall) -- <__main__.Ball object at 0x02AD2E90>
As you saw here, Python told you where the instance is defined (or __main__, A.K.A. the main part of the program), the class name (Ball2/Ball), and where Python stores it in its memory (0x02BD9570/0x02AD2E90).
If you want Python to say something you actually want to understand, you would use __str__() like this:
class Ball3:
def __init__(self, color, size, direction):
self.color = color
self.size = size
self.direction = direction
def __str__(self):
msg="This ball is a " + self.size + ", " + self.color + " ball."
return msg
theBall=Ball3("purple", "big", "down")
print(theBall)
What's with the plus signs (+)? Well, I'm not exactly sure, but you need this for a tuple. Otherwise...
Traceback (most recent call last):
File "C:/Python33/Ball3.py", line 12, in <module>
print(theBall)
TypeError: __str__ returned non-string (type tuple)
Anyway, after debugging it, it should end up doing this:
This ball is a big, purple ball.
Seems to be a lot of trouble to go through as you can always just do
print("This ball is a big, purple ball.")
But this way is an option, because you might need to describe the attributes thousands of lines of code later, and you just don't want to go back and look for it if you forget it. That's the beauty of computers: You can forget all you want.
I think I've rambled on long enough for one article. See ya later!
No comments:
Post a Comment