Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Nhập khẩu: Đôi khi bạn không thích tên của một hàm, bạn muốn nhập khẩu có lẽ bạn đã sử dụng tên cho cái gì khác. Bạn có thể sử dụng | CHAPTER 9 MAGIC METHODS PROPERTIES AND ITERATORS 179 This class defines one of the most basic capabilities of all birds eating. Here is an example of how you might use it b Bird b.eat Aaaah. b.eat No thanks As you can see from this example once the bird has eaten it is no longer hungry. Now consider the subclass SongBird which adds singing to the repertoire of behaviors class SongBird Bird def init__ self self.sound Squawk def sing self print self.sound The SongBird class is just as easy to use as Bird sb SongBird sb.sing Squawk Because SongBird is a subclass of Bird it inherits the eat method but if you try to call it you ll discover a problem sb.eat Traceback most recent call last File stdin line 1 in File birds.py line 6 in eat if self.hungry AttributeError SongBird instance has no attribute hungry The exception is quite clear about what s wrong the SongBird has no attribute called hungry. Why should it In SongBird the constructor is overridden and the new constructor doesn t contain any initialization code dealing with the hungry attribute. To rectify the situation the SongBird constructor must call the constructor of its superclass Bird to make sure that the basic initialization takes place. There are basically two ways of doing this by calling the unbound version of the superclass s constructor or by using the super function. In the next two sections I explain both techniques. Calling the Unbound Superclass Constructor The approach described in this section is perhaps mainly of historical interest. With current versions of Python using the super function as explained in the following section is clearly the way to go and with Python 3.0 it will be even more so . However much existing code uses the approach described in this section so you need to know about it. Also it can be quite instructive it s a nice example of the difference between bound and unbound methods. 180 CHAPTER 9 MAGIC METHODS PROPERTIES AND ITERATORS Now let s get down to business. If you .