简体   繁体   中英

Determinate if class has user defined __init__

I'm trying to identify if a class that i received via an argument has a user defined __init__ function in the class that was passed. Not in any super class.

class HasInit(object):
  def __init__(self):
    pass

class NoInit(object):
  pass

class Base(object):
  def __init__(self):
    pass

class StillNoInit(Base):
  pass

def has_user_defined_init_in(clazz):
  return True if # the magic

assert has_user_defined_init_in(HasInit) == True
assert has_user_defined_init_in(NoInit) == False
assert has_user_defined_init_in(StillNoInit) == False

I think this will work:

def has_user_defined_init_in(clazz):
    return "__init__" in clazz.__dict__

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM