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

Usunięta treść Dodana treść
Sasek (dyskusja | edycje)
drobne poprawki formatowania
Sasek (dyskusja | edycje)
tłumaczenie
Linia 17:
'/music/_singles/kairo.mp3'
 
# Metoda specjalna <tt>__getitem__</tt> wygląda dość prosto. Tak jak zwykłe metody <tt>clear</tt> <tt>keys</tt> i <tt>values</tt> po prostu pozwala słownikowi zwrócić swoje wartości. Jak jest wywoływana? Możesz wywołać ją bezpośrednio, ale w praktyce tak się nie robi. Chciałem Ci tylko pokazać, jak to działa. Dobrym sposobem jest pozwolenie Pythonowi, żeby wywołał ją za Ciebie.
# The __getitem__ special method looks simple enough. Like the normal methods clear, keys, and values, it just redirects to the dictionary to return its value. But how does it get called? Well, you can call __getitem__ directly, but in practice you wouldn't actually do that; I'm just doing it here to show you how it works. The right way to use __getitem__ is to get Python to call it for you.
#Takiej składni użyłbyś, by dostać wartość ze słownika i dokładnie tę wartość dostajesz. A brakujące ogniwo jest takie: wewnętrznie Python przekształcił tę składnię na wywołanie metody <tt>f.__getitem__("name")</tt>. Właśnie dlatego <tt>__getitem__</tt> jest specjalną metodą: nie tylko możesz ją zawołać ale Python woła ją za Ciebie, gdy użyjesz odpowiedniej składni.
# This looks just like the syntax you would use to get a dictionary value, and in fact it returns the value you would expect. But here's the missing link: under the covers, Python has converted this syntax to the method call f.__getitem__("name"). That's why __getitem__ is a special class method; not only can you call it yourself, you can get Python to call it for you by using the right syntax.
 
Oczywiście jest też specjalna metoda <tt>__setitem__</tt> komplementarna z <tt>__getitem__</tt>
Of course, Python has a __setitem__ special method to go along with __getitem__, as shown in the next example.
 
'''ExamplePrzykład 5.13. TheMetoda <tt>__setitem__ Special Method</tt>'''
 
def __setitem__(self, key, item): self.data[key] = item