Beginning PythonFrom Novice to Professional, Second Edition 2008 phần 4

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 Aaaah. 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 Squawk def sing self print The SongBird class is just as easy to use as Bird sb SongBird 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 Traceback most recent call last File stdin line 1 in File line 6 in eat if 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 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 .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.