Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python object Oriented creating object in main function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    class Test():
    def foo() :
        print('Hello ')

    def bar():
        foo()
        print('world')
    def run():
        test = Test()
        test.bar()

    run()

thanks in advance

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading