Reputation: 157
I am a beginner in Python. I know spaces play a significant role for compiling. So I have the following two classes in the same python script file:
class ClassA:
def __init__(self):
self.x = {}
def _methodA1():
# Something
def _methodA2():
# Something
class ClassB:
def _methodB1():
# Something
def _methodB2():
# Something
def MethodX():
print "Hello World"
(1) Which class MethodX
belongs to?
(2) Can we say ClassB
is an inner class of ClassA
?
(3) If MethodX
belongs to ClassA, does it mean self.x
is accessible via MethodX
?
Upvotes: 1
Views: 482
Reputation: 5982
Yes, space is important to python, the level of indentation used for blocks and statements is how the scope of those statements is established.
MethodX isn't a method it's a top level function, not associated with an instance of an object or called via a Class.
ClassB isn't an inner class of ClassA. You can nest classes in python, because class introduces another level of block scope, which do nest, but it's quite unusual to do so, it doesn't confer many benefits, and it makes some scoping behaviours look more confusing (i.e. referencing class attributes in the enclosing class scope)
MethodX doesn't have access to ClassA.x via self because it's not in the scope of ClassA. Furthermore, you have to declare self as an explicit parameter in python - the reference to the object instance is passed automatically as the first parameter to methods, but there is no binding automatically created for it. In fact self
is a convention, not a formal keyword. _methodA1
and _methodA2
do have method scope, because they're defined within the scope of ClassA, but they don't declare a self binding
Upvotes: 2
Reputation: 5606
Stuff with the same indentation is generally on the same "level" (unindented = "file level").
Block which is indented "belongs" to first statement before it, which is indented less than it.
Example:
class A: # "file level"
def b(self): # "belongs to" class A
if True: # "belongs to" b
pass # "belongs to" the if
def x(): # "file level"
pass # "belongs to" x
pass # same as above
Upvotes: 0
Reputation: 155363
MethodX
belongs to no class, it's a global function, not a method of one of the classesClassA
and ClassB
are at identical indentation; an inner class of ClassA
would match the indentation of the method definitions in ClassA
MethodX
has no direct access to attributes of any instance. Beyond that, self
must be explicitly accepted as the first positional argument by methods; since MethodX
doesn't accept self
, it can't access it. All of your methods are broken because of this; unless decorated with @staticmethod
, they need to accept at least one positional argument (which is called self
by convention on regular methods, and cls
by convention on @classmethod
s).Upvotes: 8
Reputation: 6785
MethodX doesn't belong to either class A or B.
ClassB is not an "inner" class of ClassB.
Irrelevant because it's not the case.
Upvotes: 1