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

Usunięta treść Dodana treść
Sasek (dyskusja | edycje)
Nie podano opisu zmian
Sasek (dyskusja | edycje)
poprawa formatowania (wcześniej tłumaczenie)
Linia 40:
# <tt>clear</tt> jest normalną metodą klasy; jest dostępna publicznie i może być wołana przez kogokolwiek w dowolnej chwili. Zauważ, że <tt>clear</tt>, jak wszystkie metody klas, ma <tt>self</tt> jako pierwszy argument. (Pamiętaj, że nie dodajesz <tt>self</tt> gdy wywołujesz metodę; Python robi to za Ciebie.) Zauważ podstawową cechę tej klasy pojemnikowej: przechowuje prawdziwy słownik (dane) jako atrybut danych (składową), definiuje wszystkie metody, które ma prawdziwy słownik i w każdej z tych metod zwraca wynik odpowiedniej metody słownika. (Gdybyś zapomniał, metoda <tt>clear</tt> słownika kasuje jego szystkie klucze i wartości.)
# metoda <tt>copy</tt> słownika zwraca nowy słownik, będący dokładną kopią oryginału (mający takie same pary klucz-wartość). Ale klasa <tt>UserDict</tt> nie może po prostu wywołać <tt>self.data.copy</tt>, ponieważ ta metoda zwraca słownik a to co chcemy tu zrobić, to zwrócenie nowej instancji klasy takiej, jak <tt>self</tt>.
# Używamy atrybutu <tt>class</tt>, żeby sprawdzić, czy <tt>self</tt> jest obiektem klasy <tt>UserDict</tt>; jeśli tak, jesteś w domu, bo wiesz jak zrobić kopię <tt>UserDict</tt>: stwórz nowy obiekt <tt>UserDict</tt> i przekaż mu słownik wyciągnięty z <tt>self.data</tt>. Wtedy możesz od razu zwrócić nowy obiekt <tt>UserDict</tt> nie wykonując nawet instrukcji <font color=blue><tt>'''import'''</tt></font> z następnej linii.
# If self.__class__ is not UserDict, then self must be some subclass of UserDict (like maybe FileInfo), in which case life gets trickier. UserDict doesn't know how to make an exact copy of one of its descendants; there could, for instance, be other data attributes defined in the subclass, so you would need to iterate through them and make sure to copy all of them. Luckily, Python comes with a module to do exactly this, and it's called copy. I won't go into the details here (though it's a wicked cool module, if you're ever inclined to dive into it on your own). Suffice it to say that copy can copy arbitrary Python objects, and that's how you're using it here.
# The rest of the methods are straightforward, redirecting the calls to the built-in methods on self.data.