如何从类的实例继承\u init\u?

2024-06-28 10:59:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想继承类实例的所有__init__。例如,如果有一个类Lens和一个Lens“L50mm”实例。我希望我的相机与“L50mm”继承所有__init__的镜头如下:

class Lens:
   def __init__(self,focallength,aperture):
       self.focallength=focallength
       self.aperture=aperture

L50mm=Lens(50,2.2)

class Camera:
    def __init__(self,name,sensor,lens='None'):
        self.name=name
        self.sensor=sensor
        if lens!='None':#if I have a lens mounted I want that all the __init__ is inherited e.g.:
            super(Lens).__init__()#something like this I KNOW it doesn't work
        else:#if I don't have a lens just keep 'None'
            self.lens=lens

mycamera=Camera('DSCF828','CCD',L50mm)
>>TypeError: must be type, not classobj

当然我知道我可以将self.lens=lens放在Camera __init__方法中,但是我想知道是否有更直接的方法来继承所有属性。你知道吗

主要目标是直接访问所有方法:

mycamera.focallength
mycamera.aperture

而不是:

mycamera.lens.aperture
mycamera.lens.focallength

相反,注释中建议的self.lens = Lens()对我来说没有任何意义,因为我必须再次传递所有参数,所以请仔细阅读问题。你知道吗


Tags: 实例方法nameselfnoneifinitsensor
3条回答

我想知道你是否真的想继承,至少不是传统的面向对象的。因为相机不是镜头,所以它们之间没有合适的超/子类型关系。你知道吗

您可能需要将lens的属性包装在Camera中。我不是说这是个好主意,但肯定有可能。您可以做的是重写__getattr__

 class Camera(object):
      def __getattr__(self, key):
            return getattr(self.lens, key)

      def __init__(self,name,sensor,lens=None):
             self.name=name
             self.sensor = sensor
             self.lens = lens

这意味着,如果您有一个camera对象cam并尝试访问它的一个成员,如果以正常方式失败,它将尝试使用getattr(self.lens, key)。例如cam.focallength在传统意义上是失败的(因为相机中没有focallength),但是它将继续尝试有效地将其转换成cam.lens.focallength。你知道吗

这可以通过组合而不是继承来实现。 这假设您知道需要从镜头获得哪些属性。你知道吗

class Camera:
    def __init__(self,name,sensor,lens=None):
        self.name=name
        self.sensor=sensor
        if lens is not None:
            self.focallength = lens.focallength
            self.aperture = lens.aperture

我的意见是你用便便的方法不对。如果你真的想这样做,可以尝试以下方法:

for attr in dir(lens):
    setattr(self, attr, getattr(attr, lens))

例如:

class Lens:
    def __init__(self, a, b):
        self.a, self.b = a, b

class Camera:
    def __init__(self, lens):
         for attr in dir(lens):
             setattr(self, attr, getattr(attr, lens))

lens = Lens(12, 13)
cam = Camera(lens)
cam.a

阅读答案的评论,你就会明白它有多脏:)

相关问题 更多 >