6

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!

1
  • Yes thank you! Kinda missed that Commented Jul 8, 2016 at 21:35

4 Answers 4

6

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
Sign up to request clarification or add additional context in comments.

7 Comments

Ok so basically, whenever referring to a variable defined outside of __init__ use classname.variablename to reference it?
A member of a class does not need to be defined in __init__. The real answer is to understand if the variable was defined by the class or the instance. If you find yourself needing to create a HelloWorld object to access the variable, which is the case with self.hello then don't use classname.variablename. Otherwise you can use classname.variablename.
@MichaelJones No, it depends on the behaviour you want to achieve. As I and mgilson show there are cases where you want to make that value overridable by instances/derived classes, and other times not. So it depends.
Ok, I guess one of the biggest issues is I am not understanding this line HelloWorld('Goodbye').hello What does that do?
The line HelloWorld('Goodbye').hello creates a HelloWorld object and then accesses the hello member belonging to that object. It is the same as object = HelloWorld('Goodbye') and then print object.hello
|
1

Generally, you'll want to use self here. This allows for a few nice "tricks" to be played. e.g. You can override hello in a subclass:

class GreetWorld(HelloWorld):
    hello = "Greetings"

Or you can re-set the attribute on a per-instance basis:

hw = HelloWorld()
hw.hello = 'Hey, How are you'

Comments

0

Both of them will work. When you have self passed in to the method self == HelloWorld

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

But when self is not passed in to method i.e, static method then use

class HelloWorld:
    hello = "hello"
    @staticmethod
    def world():
        print HelloWorld.hello

Comments

0

You can use both, the results are well defined and in that case they will do the same.

Note however that this changes when you have derived classes:

class Base:
    hello = 'A'

    def greet(self):
        print(self.hello)

    def greet2(self):
        print(Base.hello)


class Derived(Base):
    hello = 'B'

d = Derived()
d.greet()   # prints B
d.greet2()  # prints A

Moreover in some cases you could have instances that use that attribute to override the class value:

class Base:
    hello = 'A'
    def __init__(self, val=None):
        if val is not None:
            self.hello = 'B'
    def greet(self):
        print(self.hello)


A = Base()
B = Base()
A.greet()    # A
B.greet('B') # B
A.greet()    # *still* A

So if you want to be sure that the value used is precisely the one of that class use the explicit class name, otherwise use self.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.