Zanurkuj w Pythonie/Metody specjalne: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
Sasek (dyskusja | edycje)
tłumaczenie
Linia 35:
{'name':'/music/_singles/kairo.mp3', 'genre':32}
 
# LikeTak thejak <tt>__getitem__ method</tt>, metoda <tt>__setitem__</tt> simplypo redirectsprostu topozawala the real dictionarymetodzie <tt>self.data</tt> tosłownika dowykonać itsjej workpracę. AndI liketak jak w przypadku <tt>__getitem__,</tt> younie wouldn'tmusisz ordinarilywołać calljej itw directlyten like this;sposób. Python callswywoła <tt>__setitem__</tt> for you when youjeśli usetylko theużyjesz rightodpowiedniej syntaxskładni.
# Ta linia wygląda jak użycie słownika. Tylko, że <tt>f</tt> jest obiektem klasy próbującej udawać słownik a metoda <tt>__stitem__</tt> jest ważną częścią tej maskarady. Ta linia kodu powoduje właściwie wywołanie <tt>f.__setitem__("genre", 32)</tt>.
# This looks like regular dictionary syntax, except of course that f is really a class that's trying very hard to masquerade as a dictionary, and __setitem__ is an essential part of that masquerade. This line of code actually calls f.__setitem__("genre", 32) under the covers.
 
<tt>__setitem_</tt> jest metodą specjalną, ponieważ Python wywołuje ją za Ciebie, ale ciągle jest metodą klasy. Tak łatow, jak zdefiniowałeś ją w klasie <tt>UserDict</tt>, możesz ją przedefiniować w klasach pochodnych i zasłonić metodę klasy podstawowej. To pozwala Ci definiować klasy, które czasami zachowują się jak zwykły słownik ale potrafią coś więcej.
__setitem__ is a special class method because it gets called for you, but it's still a class method. Just as easily as the __setitem__ method was defined in UserDict, you can redefine it in the descendant class to override the ancestor method. This allows you to define classes that act like dictionaries in some ways but define their own behavior above and beyond the built-in dictionary.
 
This concept is the basis of the entire framework you're studying in this chapter. Each file type can have a handler class that knows how to get metadata from a particular type of file. Once some attributes (like the file's name and location) are known, the handler class knows how to derive other attributes automatically. This is done by overriding the __setitem__ method, checking for particular keys, and adding additional processing when they are found.