A piece of code works that I don't see why. It shouldn't work from my understanding. The problem is illustrated easily below:
"Main.py"
from x import * #class x is defined
from y import * #class y is defined
xTypeObj = x()
yTypeObj = y()
yTypeObj.func(xTypeObj)
"x.py"
class x(object):
def __init__...
...
def functionThatReturnsAString(self):
return "blah"
"y.py"
#NO IMPORT STATEMENT NEEDED?? WHY
class y(object):
def __init__...
...
def func(self, objOfTypeX):
print(objOfTypeX.functionThatReturnsAString())
My question is why do I NOT need to have an import statement in "y.py" of the type
from x import functionThatReturnAString()
How does it figure out how to call this method?
Python is an object-oriented programming language. In such a language, values are objects, and objects can have methods.
The functionThatReturnsAString
function is a method on a class, and objOfTypeX
is an instance of that class. Instances of a class carry with them all the methods of it's class.
This is why, for example, list
objects in python have an .append()
method:
>>> alist = []
>>> alist.append(1)
>>> alist
[1]
The list
class has a .append()
method, and you do not need to import that method to be able to call it. All you need is a reference to a list instance.
Technically speaking, a python list
is a type, but that distinction does not matter here. On the whole, types are the same things as classes, for the purpose of this discussion.
Please do go and read the Python Tutorial, it explains classes in a later chapter (but you may want to skim through the first set of chapters first).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With