user2875416
user2875416

Reputation: 15

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.

Upvotes: 0

Views: 14570

Answers (2)

Aryah Babu
Aryah Babu

Reputation: 1

in the main funtion just write - from student import Student. It is - from 'Filename' import 'Classname'

So

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

if name == 'main': main()

Upvotes: 0

lucemia
lucemia

Reputation: 6617

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()

Upvotes: 4

Related Questions