1

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)
3
  • 2
    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. Commented Jun 29, 2015 at 5:16
  • 1
    What errors are you facing? Add the entire stacktrace to your question, please. Commented Jun 29, 2015 at 5:18
  • Please also include reason of creating class instance within class declaration itself. Commented Jun 29, 2015 at 5:20

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.