Zanurkuj w Pythonie/Klasa opakowująca UserDict: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
tłumaczenie
Linia 1:
== Zgłębianie klasy <tt>UserDict</tt> <!--A Wrapper Class --> ==
 
Klasa <tt>FileInfo</tt> działa podobnie do słowniksłownika, o czym mogliśmy się już wcześniej przekonać. Aby ją lepiej zgłębić przyjrzyjmy się klasie <tt>UserDict</tt> w module <tt>UserDict</tt>, która jest przodkiem klasy <tt>FileInfo</tt>. Nie ma w niej nic specjalnego; jest to klasa napisana w Pythonie i przechowywana w pliku o rozszeżeniu .py, przypomina ona inne kody Pythona. Moduł ten jest przechowywany w katalogu <tt>lib</tt>, który z kolei znajduje się w miejsce, gdzie masz zainstalowanego Pythona.
 
{{Infobox|
Linia 15:
 
# Klasa <tt>UserDict</tt> jest klasą bazową, nie dziedziczy nic z innych klas.
# Metodę <tt>__init__</tt> nadpisaliśmy w klasie <tt>FileInfo</tt>. Zauważmy, że lista argumentów w klasie przodka jest różna niż w klasie potomka. Jest ok. Każda podklasa może mieć własny zbiór argumentów, pod warunkiem, że metody przodka będą wywoływane z poprawną ilościąpoprawnymi argumentówargumentami. Tutaj klasa przodka posiada możliwość zdefiniowania początkowych wartości (dzięki przekazaniu słownika w argumencie <tt>dict</tt>), jednak której klasa <tt>FileInfo</tt> nie wykorzystuje.
# Python supports data attributes (called “instance variables” in Java and Powerbuilder, and “member variables” in C++). Data attributes are pieces of data held by a specific instance of a class. In this case, each instance of UserDict will have a data attribute data. To reference this attribute from code outside the class, you qualify it with the instance name, instance.data, in the same way that you qualify a function with its module name. To reference a data attribute from within the class, you use self as the qualifier. By convention, all data attributes are initialized to reasonable values in the __init__ method. However, this is not required, since data attributes, like local variables, spring into existence when they are first assigned a value.
# The update method is a dictionary duplicator: it copies all the keys and values from one dictionary to another. This does not clear the target dictionary first; if the target dictionary already has some keys, the ones from the source dictionary will be overwritten, but others will be left untouched. Think of update as a merge function, not a copy function.