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

Usunięta treść Dodana treść
Sasek (dyskusja | edycje)
Tłumaczenie i poprawa formatowania
Sasek (dyskusja | edycje)
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>'''
Example 5.10. UserDict Normal Methods
 
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.)
# clear is a normal class method; it is publicly available to be called by anyone at any time. Notice that clear, like all class methods, has self as its first argument. (Remember that you don't include self when you call the method; it's something that Python adds for you.) Also note the basic technique of this wrapper class: store a real dictionary (data) as a data attribute, define all the methods that a real dictionary has, and have each class method redirect to the corresponding method on the real dictionary. (In case you'd forgotten, a dictionary's clear method deletes all of its keys and their associated values.)
# 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>.
# The copy method of a real dictionary returns a new dictionary that is an exact duplicate of the original (all the same key-value pairs). But UserDict can't simply redirect to self.data.copy, because that method returns a real dictionary, and what you want is to return a new instance that is the same class as self.
# YouUżywamy useatrybutu the<tt>class</tt>, __class__żeby attributesprawdzić, toczy see<tt>self</tt> ifjest self isobiektem aklasy <tt>UserDict</tt>; ifjeśli sotak, you'rejesteś goldenw domu, becausebo youwiesz knowjak howzrobić to copy akopię <tt>UserDict</tt>: juststwórz createnowy a newobiekt <tt>UserDict</tt> andi giveprzekaż itmu thesłownik realwyciągnięty dictionary that you've squirreled away inz <tt>self.data</tt>. ThenWtedy youmożesz immediatelyod returnrazu thezwrócić newnowy obiekt <tt>UserDict</tt> younie don'twykonując evennawet getinstrukcji to the<font color=blue>import</font> copy on thez nextnastępnej linelinii.
# 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.