Zanurkuj w Pythonie/locals i globals: Różnice pomiędzy wersjami
Usunięta treść Dodana treść
mNie podano opisu zmian |
zaczynam tłumaczyć |
||
Linia 1:
{{Podświetl|py}}
== <tt>locals</tt>
Odejdźmy teraz na minutkę od przetwarzania HTML-u. Porozmawiajmy o tym, jak Python obchodzi się ze zmiennymi. Python posiada dwa wbudowane funkcje, <tt>locals</tt> i <tt>globals</tt>, które pozwalają nam uzyskać w słownikowy sposób dostęp do zmiennych lokalnych i globalnych.
Pamiętasz <tt>locals</tt>? Pierwszy raz zobaczyłeś to tutaj:
def unknown_starttag(self, tag, attrs):
strattrs = "".join([' %s="%s"' % (key, value) for key, value in attrs])
self.pieces.append("<%(tag)s%(strattrs)s>" % locals())
Nie, czekaj, nie mogłeś jeszcze się uczyć o <tt>locals</tt>. Najpierw, musisz nauczyć się, czym są przestrzenie nazw. Przedstawimy teraz trochę suchego materiału, lecz ważnego, dlatego też zachowaj uwagę.
Python uses what are called namespaces to keep track of variables. A namespace is just like a dictionary where the keys are names of variables and the dictionary values are the values of those variables. In fact, you can access a namespace as a Python dictionary, as you'll see in a minute.
Linia 50 ⟶ 48:
# Remember, Python has dynamic typing, so you could just as easily pass a string in for arg; the function (and the call to locals) would still work just as well. locals works with all variables of all datatypes.
What locals does for the local (function) namespace, globals does for the global (module) namespace. globals is more exciting, though, because a module's namespace is more exciting <ref>I don't get out much</ref>.
Remember the difference between from module import and import module? With import module, the module itself is imported, but it retains its own namespace, which is why you need to use the module name to access any of its functions or attributes: module.function. But with from module import, you're actually importing specific functions and attributes from another module into your own namespace, which is why you access them directly without referencing the original module they came from. With the globals function, you can actually see this happen.
Linia 104 ⟶ 102:
# This prints z= 8, not z= 7.
'''Przypisy'''
<references />
|