Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between calling method with self and with class name?

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.

like image 410
d9h Avatar asked Mar 10 '23 04:03

d9h


1 Answers

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.

like image 114
noɥʇʎԀʎzɐɹƆ Avatar answered May 01 '23 08:05

noɥʇʎԀʎzɐɹƆ