Zanurkuj w Pythonie/Klasa opakowująca UserDict: Różnice pomiędzy wersjami
Usunięta treść Dodana treść
Tłumaczenie i poprawa formatowania |
Nie podano opisu zmian |
||
Linia 9:
class UserDict: <font color=red>#(1)</font>
def __init__(self, dict=None): <font color=red>#(2)</font>
self.data = {} <font color=red>#(3)</font>
if dict is not None: self.update(dict) <font color=red>#(4) (5)</font>
# Klasa <tt>UserDict</tt> jest klasą bazową, nie dziedziczy nic z innych klas.
Linia 26:
Zawsze przypisuj wartość początkową wszystkim zmiennym obiektu w jego metodzie <tt>__init</tt>. Oszczędzi to godzin debugowania w poszukiwaniu wyjątków <tt>AtributeError</tt> powodowanych przez odwołania do niezainicjowanych (czyli nieistniejących) atrybutów.}}
'''Przykład 5.10. Standartowe metody klasy <tt>UserDict</tt>'''
def clear(self): self.data.clear() <font color=red>#(1)</font>
def copy(self): <font color=red>#(2)</font>
if self.__class__ is UserDict: <font color=red>#(3)</font>
return UserDict(self.data)
import copy <font color=red>#(4)</font>
return copy.copy(self)
def keys(self): return self.data.keys() <font color=red>#(5)</font>
def items(self): return self.data.items()
def values(self): return self.data.values()
# <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>.
#
# 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.
|