john-science / python_for_scientists

Python Open Courseware for Scientists and Engineers
GNU General Public License v3.0
68 stars 40 forks source link

OOP part 2, abstract methods #66

Closed maybuhleen closed 5 years ago

maybuhleen commented 5 years ago

Python 3 does not complain when you don't include an abstract method within a subclass that inherits from the base class with the abstract method. Tried this in iPython and Jupyter: no complaints. Am I doing something wrong?

Python 2 still complains as you would expect.

john-science commented 5 years ago

Eww. I'm not sure that change is an improvement. I will try it myself and fix the lecture accordingly.

Good catch!

maybuhleen commented 5 years ago

Here's the workaround Xue and I found.

from abc import ABCMeta, abstractmethod import six

@six.add_metaclass(ABCMeta) class Polygon: def init(self, n): self.number_of_sides = n

def print_num_sides(self):
    print('There are ' + str(self.number_of_sides) + ' sides.')

@abstractmethod
def get_area(self):
    raise NotImplementedError

On Wed, Dec 19, 2018 at 3:34 PM John Stilley notifications@github.com wrote:

Eww. I'm not sure that change is an improvement. I will try it myself and fix the lecture accordingly.

Good catch!

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/theJollySin/python_for_scientists/issues/66#issuecomment-448789573, or mute the thread https://github.com/notifications/unsubscribe-auth/AJ3TQCtwu16dza4qfUwYtItwGNFbMYd-ks5u6s0CgaJpZM4Zax4A .

john-science commented 5 years ago

That's an interesting solution!

After playing around with it a bit, I think the easier solution is to do "from abc import ABC":

from abc import ABC, abstractmethod

class Polygon(ABC):
    def __init__(self, n):
        self.number_of_sides = n

After some testing, it appears that does the same thing that all that "ABCMeta" stuff did in Python 2. This solution works in Python 3, but I bet doesn't in Python 2. Still, it looks like this is how the developers of the abc module expect us to work now.

I have updated the lecture and problem sets. Tell me if I botched something!

Thanks so much!