如何从基类获取派生类名称 [英] how to get derived class name from base class

查看:328
本文介绍了如何从基类获取派生类名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类Person和派生类ManagerEmployee.现在,我想知道的是创建的对象是Manager还是Employee.

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.

此人如下:

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"

对于Employee,标题为"Employee".创建Person时,它是ManagerEmployee.当我获得人员对象时,该类是人员",但我想知道它是来自派生类经理"还是员工".

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'.

推荐答案

不确定我是否理解您的要求,但是您可以使用x.__class__.__name__以字符串的形式检索类名,例如

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.

class Person:
    pass

class Manager(Person):
    pass

class Employee(Person):
    pass

def get_class_name(instance):
    return instance.__class__.__name__

>>> m = Manager()
>>> print get_class_name(m)
Manager
>>> print get_class_name(Employee())
Employee

或者,您可以使用isinstance检查不同的类型:

Or, you could use isinstance to check for different types:

>>> print isinstance(m, Person)
True
>>> print isinstance(m, Manager)
True
>>> print isinstance(m, Employee)
False

因此您可以执行以下操作:

So you could do something like this:

def handle_person(person):
    if isinstance(person, Manager):
        person.read_paper()     # method of Manager class only
    elif isinstance(person, Employee):
        person.work_hard()      # method of Employee class only
    elif isinstance(person, Person):
        person.blah()           # method of the base class
    else:
        print "Not a person"

这篇关于如何从基类获取派生类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆