预计阅读本页时间:-
Step 6: Using Introspection Tools
Let’s make one final tweak before we throw our objects onto a database. As they are, our classes are complete and demonstrate most of the basics of OOP in Python. They still have two remaining issues we probably should iron out, though, before we go live with them:
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
- First, if you look at the display of the objects as they are right now, you’ll notice that when you print tom the Manager labels him as a Person. That’s not technically incorrect, since Manager is a kind of customized and specialized Person. Still, it would be more accurate to display objects with the most specific (that is, lowest) classes possible.
- Second, and perhaps more importantly, the current display format shows only the attributes we include in our __str__, and that might not account for future goals. For example, we can’t yet verify that tom’s job name has been set to mgr correctly by Manager’s constructor, because the __str__ we coded for Person does not print this field. Worse, if we ever expand or otherwise change the set of attributes assigned to our objects in __init__, we’ll have to remember to also update __str__ for new names to be displayed, or it will become out of sync over time.
The last point means that, yet again, we’ve made potential extra work for ourselves in the future by introducing redundancy in our code. Because any disparity in __str__ will be reflected in the program’s output, this redundancy may be more obvious than the other forms we addressed earlier; still, avoiding extra work in the future is generally a good thing.