1

I'm learning python on my own out of interest, but I face a lot of questions when I get into "class".

In this post: What happens when you initialise instance variables outside of __init__

The answer by Dietrich Epp gave out a detailed explanation of what really happens in a class. Dietrich said that the three cases in the editor are the same.

However, when I type the following things in command line:

# Set inside __init__
class MyClassA:
    def __init__(self):
        self.x = 0
objA = MyClassA()

# Set inside other method
class MyClassB:
    def my_initialize(self):
        self.x = 0
objB = MyClassB()
objB.my_initialize()

# Set from outside any method, no self
class MyClassC:
    pass
objC = MyClassC()
objC.x = 0

print(objA.x)
print(objB.my_initialize())
print(objC.x)

It turns out that the middle of the printing result is 'none' which means that instead of giving out 0, objB.my_initialize() return to none.

Can anyone help explain this? It seems that the three cases are somehow different to me...

cindy50633
  • 144
  • 2
  • 11
  • 2
    If you called `objA.__init__()` it *too* would print `None`.. You are printing the return value of a method, **not the attribute the method set**. – Martijn Pieters Mar 24 '18 at 15:17

1 Answers1

2

For objB, you need to call the function first, then get the value of x. So your code goes from

print(objB.my_initialize())

to

objB.my_initialize()
print(objB.x)

This is because objB.my_initialize() only sets the value of x, and doesn't return anything, hence why you are getting None.

dangee1705
  • 3,445
  • 1
  • 21
  • 40
  • 1
    For clarity, the default return value of Python functions/methods without an explicit return value is `None` – EmmEff Mar 24 '18 at 15:17