damon
damon

Reputation: 8477

adding a field to subclass in python

I have a base class

class Person(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def title(self):
        return self.name+str(self.age)

I need to subclass this to get an Employee class where an empid is also an attribute

class Employee(Person):
    def __init__(self,*args,**kwargs,empid):
        Person.__init__(self, *args)
        self.empid= empid
    def title(self):
        return self.name+str(self.age)+self.empid

For example , suppose Jon is an Employee with empid="001"

j = Employee('Jon',30,'001')
print j.title()

should give Jon30001

I am getting a syntax error..Am I doing the subclassing wrong?

Upvotes: 1

Views: 1869

Answers (1)

Andbdrew
Andbdrew

Reputation: 11895

Optional arguments must come last in a method signature. There is also an indentation problem in your original post, but it looks like it was a copy/paste error while posting. The following should work better for you.

[EDIT]

class Person(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def title(self):
        return self.name+str(self.age)

class Employee(Person):
    def __init__(self,*args,**kwargs):
        Person.__init__(self, *args)
        self.empid= kwargs.get('empid')
    def title(self):
        return self.name+str(self.age)+self.empid

output ->

>>> j = Employee('Jon',30,empid="001")
>>> j.title()
'Jon30001'

Upvotes: 1

Related Questions