Portál AbcLinuxu, 12. května 2025 06:46
Ahoj,
Mam problem s pythonem, vytvoril jsem si par trid a napsal program, ktery ve vysledku funguje nejak divne. Nakonec jsem zjistil, ze kdyz vytvarim instanci nejake tridy, ktera ma v konstruktoru defaultni hodnotu, tak pri vytvoreni druhe instance stejne tridy se mi do defaultniho parametru vnuti hodnota z predchozi instance. Nevite jak to resit, aby to nedelal ? (docla mne s tim otravuje programovani)
Priklad:
<pre>
>>> class A:
... def __init__(self, seznam = []):
... self.seznam = seznam
... print seznam
... print self.seznam
... def append(self, item):
... self.seznam.append(item)
...
>>> a = A()
[]
[]
>>> a.append('ahoj')
>>> b = A()
['ahoj'] # Tady by se podle mne melo zobrazit: []
['ahoj'] # Tady taktez, jako pri vytvareni instance "a", ale vnuti se tam neco ineho :o(
>>>
</pre>
Dik za kazdy tip
No to je v případě, že deaultní hodnota není imutable. Stím jsem si taky užil své :)
... Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:
def whats_on_the_telly(penguin=None): if penguin is None: penguin = [] penguin.append("property of the zoo") return penguin
Diky za vysvetleni.
Zkousel jsem i defaultni parametr s None, ale taky mi to nechtelo fungovat...
Az pri precteni tohoto vytahu z clanku mi doslo, ze pouzivam tridy vznikle dedenim ze zakladni - pricemz v zakladni (rodicovske) jsem to opravil ale v potomcich jsem nechal puvodni zapis.
self.seznam = seznamdát
self.seznam = seznam[:]když seznam zkopírujete, bude mít každá instance svůj - samozřejmě pokud chcete jen nastavit prázdný seznam, bude lepší to udělat v těle té metody a nepoužívat k tomu defaultní hodnotu.
Diky za tip
Duvod proc tam mam defaultni hodnotu parametru, je kvuli komplexnosti pouziti - aby slo data v urcitych pripadech (ve kterych je to vyhodnejsi) vkladat pri vytvareni instance...
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.