0

I have two classes. Engine is a parent class and Car is a child class. I defined property and setter for the property in Engine class. I want to get value of a property or change it from child class (Car).

Here is the example I work with:

#!/usr/bin/env python3

import sys

class Engine:
    def __init__(self):
        self.__cylinder = 4

    @property
    def cylinder(self):
        return self.__cylinder
    @cylinder.setter
    def cylinder(self,cylinder):
        self.__cylinder = cylinder

    def start(self):
        print("Engine started.")

    def stop(self):
        print("Engine stopped.")

class Car(Engine):
    def __init__(self):
        self.__wheel = 4
        print("How many cylinders? - " + str(Engine.cylinder))

    @property
    def wheel(self):
        return self.__wheel
    @wheel.setter
    def wheel(self, wheel):
        self.__wheel = wheel

    def drive(self):
        self.start()
        print("Car is driving")

    def stop(self):
        print("Car stopped")

class Tandem(Car):
    pass

def main():
    car = Car()
    #print("How many cylinders? - " + str(car.cylinder))

if __name__ == "__main__":
    main()
sys.exit(0)

The print in Car class (init function) gives this:

How many cylinders? - <property object at 0x10b754a48>

And if I uncomment print in main function it gives me error:

Traceback (most recent call last):
  File "./test62.py", line 49, in <module>
    main()
  File "./test62.py", line 46, in main
    print("How many cylinders? - " + str(car.cylinder))
  File "./test62.py", line 11, in cylinder
    return self.__cylinder
AttributeError: 'Car' object has no attribute '_Engine__cylinder'

What do I do wrong in each of these prints?

  • 1
    Your subclass (`Car`) overrides the `__init__` method but doesn't call `super().__init__()`. If you make that the first line of the `Car.__init__` function, it should work as you expect it to. As for your other issue, `Engine.cylinder` is the property object coming from the class rather than its result on an instance. – jonafato Jan 11 '19 at 19:46
  • Aha, clear. Here is how it should look like then: `super(Engine,self).__init__()` I prefer this way since I may have more then one parent classes to encapsulate. What about my `print` inside `__init__` function. Is there a way to print a value instead of a reference to the object? –  Jan 11 '19 at 23:46
  • Actually I was wrong. Here is the link [https://stackoverflow.com/questions/26927571/multiple-inheritance-in-python3-with-different-signatures] to the conversation where I found solution for multiple inheritance. But I still do not quite understand how to get value and not the object when use methods inside the class. –  Jan 12 '19 at 00:35
  • Are you referring to the `How many cylinders? - ` message? You need to change `Engine.cylinder` to `self.cylinder` to refer to the instance's actual property rather than the class wrapper. – jonafato Jan 17 '19 at 17:14

0 Answers0