I have a base class Person
and derived classes Manager
and Employee
. Now, what I would like to know is the object created is Manager
or the Employee
.
The person is given as belows:
from Project.CMFCore.utils import getToolByName
schema = getattr(Person, 'schema', Schema(())).copy() + Schema((TextField('FirstName', required = True, widget = StringWidget(label='First Name', i18n_domain='project')), TextField('Last Name', required = True, widget = StringWidget(label='Last Name', i18n_domain='i5', label_msgid='label_pub_city'))
class Manager(BaseContent):
def get_name(self):
catalog = getToolByName(self, "portal_catalog")
people = catalog(portal_type='Person')
person={}
for object in people:
fname = object.firstName
lname = object.lastName
person['name'] = fname+' '+ lname
# if the derived class is Employee then i would like go to the method title of employee and if its a Manager then go to the title method of Manager
person['post'] = Employee/Manager.title()
return person
For Manager and employees they are like (employee is also similar but some different methods)
from Project.Person import Person
class Manager(Person):
def title(self):
return "Manager"
For Employee the title is 'Employee'. When I create a Person
it is either Manager
or the Employee
. When I get the person object the class is Person but I would like to know whether it is from the derived class 'Manager' or 'Employee'.
Python objects provide a
__class__
attribute which stores the type used to make that object. This in turns provides a__name__
attribute which can be used to get the name of the type as a string. So, in the simple case:Would give:
'B'
So, if I follow your question correctly you would do:
The best way to "do this" is to not do it. Instead, create methods on Person that are overridden on Manager or Employee, or give the subclasses their own methods that extend the base class.
If you find yourself needing to know in the base class which subclass is being instantiated, your program probably has a design error. What will you do if someone else later extends Person to add a new subclass called Contractor? What will Person do when the subclass isn't any of the hard-coded alternatives it knows about?
Not exactly sure that I understand what you are asking, but you can use
x.__class__.__name__
to retrieve the class name as a string, e.g.Or, you could use isinstance to check for different types:
So you could do something like this:
I don't know if this is what you want, and the way you'd like it implemented, but here's a try:
Pros: only one definition of the
_type
method.In your example you do not need to know the class, you just call the method by referring to the class instance:
But do not use
object
as a variable name, you hide the built-in name.Would you be looking for something like this?