Mayank Jain
Mayank Jain

Reputation: 379

How to create object inside the same python class

I'm trying to create an object as created below obj1 i.e. inside the Employee class itself. But I'm facing errors in such object creation.

class Employee:
    'Common base class for all employees'
    empCount = 0

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1

    def displayCount(self):
        print "Total Employee %d" % Employee.empCount

    def displayEmployee(self):
        print "Name : ", self.name,  ", Salary: ", self.salary

obj1 = Employee("Mayank",6000)

Upvotes: 1

Views: 10199

Answers (3)

Salai V V
Salai V V

Reputation: 15

Well, first of all, why do you ever want to create an object inside the class itself. You can just unindent the line where you are creating your object 'obj1', and everything would work just fine.

Upvotes: -1

Jay Bosamiya
Jay Bosamiya

Reputation: 3229

As @g.d.d.c mentioned

You can't have a class variable that's an instance of the class you're defining. The class doesn't exist at the time when you're attempting to create an instance of it.

However, if you do indeed want to do something like this, here's a work-around:

Change the line

   obj1 = Employee("Mayank",6000)

to

Employee.obj1 = Employee("Mayank",6000)

Note: I don't think that you would want to write code like this, however. In this case, it makes more sense to create an object of the class outside the class. For that, it would only be an unindent of the line.

Upvotes: 2

Raymond Hettinger
Raymond Hettinger

Reputation: 226734

The problem looks to be simple. Just unindent the line, obj1 = Employee("Mayank",6000). After it is created, you can add it back to the class with Employee.obj1 = obj1.

The reason for the extra step is that normally just can't create an instance of a class inside the class definition. Otherwise, you're calling a class that hasn't been defined yet. Accordingly, the solution is to make the instance outside the class definition and then add it back after the fact :-)

Upvotes: 1

Related Questions