pythonobject

Create an object of another class python


So I have 1 package student with one class Student and I have a main.py outside that package and I'm trying to create an object of Student example

class Student:
    Id=""

    def __init__(self, Id):
        self.Id = Id

Separate File main.py:

 def main():
        print("is workign")
        temp =  Student("50")  ## I want to create the object of class Student and send an attribute

if __name__ == '__main__':
    main()

Any help will be appreciated.


Solution

  • While the class defined outside of your code, the class needs to be imported. Assume main.py and student.py are in the same folder:

    student.py

    class Student:
        Id=""
    
        def __init__(self, Id):
            self.Id = Id
    


    main.py

    def main():
        from student import Student
        print("is workign")
        temp =  Student("50")  ## I want to create the object of class Student and send an attribute
    
    if __name__ == '__main__':
        main()