Python object-oriented creating object in main function

Question:

I’m new to object oriented in Python, I’m a bit confused on how to work with object oriented.

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()
Asked By: maryam_hallal

||

Answers:

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()
Answered By: Jordan Hyatt

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.

Answered By: chepner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.