class A:
def __init__(self, text):
self.printStats()
A.printStats(text)
def printStats(self):
print(self)
a = A("Hello")
This prints:
<A object at 0x7f47e2f08ac8>
Hello
Why is this (A.printStats(text)
) possible? I understand what is happening (self
references text
), but I don't understand why.
A.printStats(text)
does NOT call printStats
with an instance of A
. It calls it with a string - no self
is passed.
def printStats(self):
# <--- here, "self" if the string "Hello", not an instance of A.
print(self)
A.printStats(self)
is equivalent to self.printStats
. Likewise if you have a function printStatsWithPrefix
;
class A:
def printStatsWithPrefix(self, prefix):
... # function body goes here
you'd have to do A.printStatsWithPrefix(self, prefix)
.
A note on style: By Python convention (PEP 8), you should use lowercase_with_underscores
for function names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With