Portál AbcLinuxu, 3. listopadu 2025 04:17
class foo(object):
def __init__(self):
self.num = '111'
def bar():
return self.num
obj = foo()
number = obj.bar()
Řešení dotazu:
def bar(): def bar(self): # Takhle by to mělo fungovat
bar deklaruj takto:
def bar(self):
return self.num
Při zavolání metody (obj.bar()) jí Python jako 1. argument dá právě ten obj (který bude uvnitř metody vidět jako self). Btw, nemusíš tomu říkat zrovna self, je to jen konvence. Můžeš používat klidně this nebo karel, a v Pythonu 3 i třeba čeněk
No, nedostane, protože už jen samotné volání obj.bar() neprojde (chybí argument reference na object):
python test.py
Traceback (most recent call last):
File "test.py", line 11, in <module>
number = obj.bar()
TypeError: bar() takes no arguments (1 given)
In [1]: class foo(object): ...: ...: def __init__(self): ...: self.num = '111' ...: def bar(self): ...: return self.num ...: In [2]: obj = foo() In [3]: obj Out[3]: <__main__.foo at 0x000000008828> In [4]: number = obj.bar() In [5]: number Out[5]: '111'
class foo(object):
def __init__(self):
self.num = '111'
def bar(self):
return self.num
obj = foo()
number = obj.bar()
print number
vypíše "111" a funguje bez chyby.
Tak jak to máš napsané v dotazu, není metoda bar členem třídy foo. Pokud má být členem, je třeba doplnit jako první argument odkaz na self object. Zkrátka tak, jak ti tady bylo už několikrát porazeno.
Nehledě na to, že každý rozumný editor pythonu by ti to poradil rovnou při psaní, nebo (pokud je úkolem to psát v plain text editoru) na to stačí poštvat pylint:
E: 6, 4: Method has no argument (no-method-argument) E: 7,15: Undefined variable 'self' (undefined-variable)
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.