简体   繁体   English

如何使用子类的数据调用超类方法?

[英]How can I call superclass method with data from subclass?

I'm parsing data from an XML file and I need to convert some of it to integers - when setting them to attributes of the B class.我正在解析 XML 文件中的数据,我需要将其中的一些转换为整数 - 将它们设置为 B 类的属性时。 Since I have multiple subclasses, I'm trying to write the code once in the superclass instead of having to write it in each subclass.由于我有多个子类,因此我尝试在超类中编写一次代码,而不必在每个子类中编写代码。

class A:

  def __setattr__(self, name, value):
    if isinstance(__class__.__dict__[name], int):
      self.__dict__[name] = int(value)

class B(A):

  val = int()

  def __init__(self, val):
    self.val = val


b = B("4")
print(type(b.val))

My problem is that __class__ and self refer to the superclass.我的问题是__class__self指的是超类。 I need the ones from the subclasses.我需要子类中的那些。 Any ideas?有任何想法吗?


I'm not sure if I explain my problem very well, so here is the code if I had to do it only for one class:我不确定我是否很好地解释了我的问题,所以如果我只需要为一个班级做这件事,这里是代码:

class A:
  val = int()

  def __init__(self, val1): #val1 is a string
    self.val = val1

  def __setattr__(self, name, value):
    if isinstance(A.__dict__[name], int):
      self.__dict__[name] = int(value)

b = A("4")
print(type(b.val)) #prints <class 'int'>

Use a classmethod to get the derived class and pass the known self as a parameter使用classmethod方法获取派生类并将已知的self作为参数传递

class A:

  def __setattr__(self, name, value):
    self._setter(self, name, value)

  @classmethod
  def _setter(cls, self, name, value):
      if isinstance(getattr(cls, name), int):
         self.__dict__[name] = int(value)

class B(A):

  val = int()

  def __init__(self, val):
    self.val = val


b = B("4")
print(type(b.val), b.val)

Instead of assigning a variable and using its type, you could just assign the type itself in the class.您可以只在类中分配类型本身,而不是分配变量并使用其类型。 I've put it all in a dict called schema because that seems to document better what is going on to me.我把它全部放在一个名为schema的字典中,因为它似乎更好地记录了我正在发生的事情。

class A:

  schema = {}

  def __setattr__(self, name, value):
    self._setter(self, name, value)

  @classmethod
  def _setter(cls, self, name, value):
      if name in cls.schema:
          value = cls.schema[name](value)
      self.__dict__[name] = value

class B(A):

  schema = {"val":int}

  def __init__(self, val):
      self.val = val

b = B("4")
print(type(b.val), b.val)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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