Mar-08-2020, 05:46 AM
I have a class that uses slots (not the class shown below). The class has a generator that iterates through the attributes and returns those of a certain type.
I know I should only ask one question at a time, but this is so closely related..
I have a class (CClass above) that inherits from my base class (AClass). When I search for numbers it unsurprisingly only finds the numbers in the slots added by CClass. I would like to find the numbers from the AClass slots too.
I did play around with using the mro. That works but is ugly. I tried using dir(), but that searches all the attributes up to class object. I tried having numbers call super(), but that didn't work and wasn't what I wanted anyway. I would like CClass to execute numbers using his superclass's slots (call same method wit supers' class data), not call the superclass's method with my slots.
class AClass: __slots__ = ('a', 'b', 'c') def __init__(self, a, b, c): super().__init__() self.a = a self.b = b self.c = c def numbers(self): for attr in self.__slots__: value = getattr(self, attr) if type(value) in (int, float): yield value class BClass: def __init__(self, a, b, c): super().__init__() self.a = a self.b = b self.c = c def numbers(self): for value in self.__dict__.values(): if type(value) in (int, float): yield value class CClass(AClass): __slots__ = ('d', 'e') def __init__(self, a, b, c, d, e): super().__init__(a, b, c) self.d = d self.e = e a = AClass('Word', 123, ('a','tuple')) b = BClass('Word', 123, ('a','tuple')) c = CClass('Word', 123, ('a','tuple'), 5.2, [1, 2, 3]) for number in a.numbers(): print('a contains', number) for number in b.numbers(): print('b contains', number) for number in c.numbers(): print('c contains', number)I like the way BClass.numbers skips the step of using the key to get the value. All I care about are the values. But I cannot figure out how to do this with slots. I again get the feeling that there's something I am missing?
I know I should only ask one question at a time, but this is so closely related..
I have a class (CClass above) that inherits from my base class (AClass). When I search for numbers it unsurprisingly only finds the numbers in the slots added by CClass. I would like to find the numbers from the AClass slots too.
I did play around with using the mro. That works but is ugly. I tried using dir(), but that searches all the attributes up to class object. I tried having numbers call super(), but that didn't work and wasn't what I wanted anyway. I would like CClass to execute numbers using his superclass's slots (call same method wit supers' class data), not call the superclass's method with my slots.