-2

I am new to Python and to OOP concept. I was doing a EdX course and came across this code. I have modified it a little bit here. But I need to understand what exactly is happening here.

Question-1: Why does print(baba.x) give 7 but not 3?

Question-2: What does print(X) (capital X) do here? In getX and init I am using 'x' and not 'X'. So where does print(X) get its value from? It seems it is getting this value from the X=7 assignment. But isn't that assignment happening outside of the method getX and also outside of the class Weird. So why is getX able to access X=7 value?

I have searched on scope in Python, but was getting too complicated for me.

class Weird(object):
    def __init__(lolo, x, y): 
        lolo.y = y
        lolo.x = x
    def getX(baba,x):
        print (baba.x)
        print (x)
        print (X)

X = 7
Y = 8

w1 = Weird(X, Y)
print(w1.getX(3))

The output of the above code is:

7
3
7
None
quietboy
  • 159
  • 11
  • why `baba` - the instance is normally called `self` – Patrick Artner Aug 11 '19 at 09:42
  • also: why `lolo` - should be `self` as well. dont confuse yourself with names - follow conventions. and read about classes and classattributes. – Patrick Artner Aug 11 '19 at 09:43
  • I have intentionally removed 'self' because so many "selfs" were confusing me and hampering my ability to learn the concepts of Classes/Methods. – quietboy Aug 11 '19 at 09:43
  • `self` is the class instance that is automatically provided for instance methods. it is confusing to change that to arbritary other names... – Patrick Artner Aug 11 '19 at 09:44

1 Answers1

0

Read What is the purpose of the word 'self', in Python?

class Weird(object):

    def __init__(self, x, y): 
        self.y = y
        self.x = x

    def getX(self,x):
        print (self.x)  # this is the x value of this instance
        print (x)       # this is the x value you provide as parameter
        print (X)       # this might read the global X  

X = 7             
Y = 8             

w1 = Weird(X, Y)   # this sets   w1.x to X (7) and w1.y to Y (8)
print(w1.getX(3))  # this provides 3 as local x param and does some printing
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69