Michael Jones Michael Jones - 4 months ago 8
Python Question

In Python OOP When Calling Class Variable Should self or Class Name be used?

I am very rusty on OOP. Now my question is, how exactly would I go about calling a class variable?

I know to call an

__init__
variable you would do the following:

class HelloWorld:

def __init__(self):
self.hello = "Hello"

def world(self):
print self.hello + "World"


How do I call a variable not initialized in the class though? Which of the following would be correct?

class HelloWorld:

hello = "Hello"

def world(self):
#Do I use self?
print self.hello + "World"
#Do I use the class name?
print HelloWorld.hello + "World"


I am just confused on whether I should be using
self
or the class name. Most examples I see are using
self
, but the one on Tutorials Point uses the class's name. Please elaborate, thank you!

Answer

HelloWorld.hello does not require an instance of HelloWorld to be used. This might be used in a case where a value should be common among all instances of HelloWorld. self.hello belongs to the instance and could be different across instances of HelloWorld.

The code

class HelloWorld:

    hello = "Hello"

    def __init__(self, text):
        self.hello = text

    def world(self):
        #Do I use self?
        print self.hello + "World"
        #Do I use the class name?
        print HelloWorld.hello + "World"

print HelloWorld.hello
print HelloWorld('Goodbye').hello

MyInstance = HelloWorld('Goodbye')
MyInstance.world()

outputs

Hello
Goodbye
GoodbyeWorld
HelloWorld
Comments