I'm new to object oriented in python, I'm a bit confused on how to work with object oriented I'm still new to stackoverflow so please don't vote down the post.
class Beta(object):
def __init__(self,message='defualt msg'):
self.message = message
def foo(self):
return self.message
def main():
beta1 = Beta()
messege = beta1.foo()
if __name__ == '__main__':
main()
The following code returns the following error NameError: name 'Beta' is not defined
but the following code work:
from time import sleep
def foo(data):
print("Beginning data processing...")
modified_data = data " that has been modified"
sleep(3)
print("Data processing finished.")
return modified_data
def main():
data = "My data read from the Web"
print(data)
modified_data = foo(data)
print(modified_data)
if __name__ == "__main__":
main()
the only difference is the class can we create an object inside the main or call the functions from the main directly or we need to explicitly create an object outside the class. in java or c# we can use the class name in any class function to call for another functions, while in python this is not working this is a script that generated the same error.
class Test():
def foo() :
print('Hello ')
def bar():
foo()
print('world')
def run():
test = Test()
test.bar()
run()
thanks in advance
CodePudding user response:
You defined your main function (and its call) inside the class itself...I think this is what you wanted...
class Beta(object):
def __init__(self,message='defualt msg'):
self.message = message
def foo(self):
return self.message
def main():
beta1 = Beta()
message = beta1.foo()
if __name__ == '__main__':
main()
CodePudding user response:
The correct indentation would be
class Beta(object):
def __init__(self,message='defualt msg'):
self.message = message
def foo(self):
return self.message
def main():
beta1 = Beta()
messege = beta1.foo()
if __name__ == '__main__':
main()
The function main
uses Beta
; it should not be part of Beta
. Likewise, the if
statement ensures that main
is only executed when the file is used as a script and not when it is imported, so is similarly not part of the class Beta
.