why does also greet has to have (self) ?
Other program languages use @
to define different class attribute however python uses self
for this. self
is used within a class to let the class know that there is a class attribute or method that can be accessed from anywhere in the class (or from outside the class).
Example benefit: If we have a function that updates a variable and a call to that function we will need to use global
and the call to the function must occur after the function has been defined in the code.
like this:
x = 0
def update_x():
global x
x+=1
print(x)
update_x()
However in a class we can avoid the use of global
and define all of our methods (functions in a class using self) after the code that calls those methods allowing us to keep things a little cleaner.
Like this:
class MyClass():
def __init__(self):
self.x = 0
self.update_x()
def update_x(self):
self.x +=1
print(self.x)
MyClass()
how do I call (is call the right word here?) greet from another py file?
You will need to import the file just like you would import a library.
For example if say your main program is in main.py
and have another py
file in the same directory called test.py
and you wish to call on something in the test.py
file from the main.py
file you will need to import the test.py
file on the main.py
file
For most cases of files that fall under the same directory do this:
import test
Sometimes your program is in a package of some kind and you may need to provide the import like this.
import package_name.test
you can use this as a test example:
test.py
file contains:
def plus_one(number):
x = number + 1
return x
main.py
file contains:
import test
x = test.plus_one(5)
print(x)
Console output should be:
6