问题描述:

Are Mixin classes abstract base classes? In the example below, the calls to test_base would fail because python wouldn't be able to resolve self.assertEqual for example.

Also, is PyCharm incorrect as flagging Mixin classes like the one below has having unresolved attribute errors?

class TestConverterMixin(object):

def setUp(self):

self.alt_hasher = getattr(hash, self.converter.__class__.__name__)

def test_base(self):

with self.settings(PASSWORD_HASHERS=[self.hasher, ]):

load_hashers(settings.PASSWORD_HASHERS)

for password in PASSWORDS:

orig = self.alt_hasher.encrypt(password)

conv = self.converter.from_orig(orig)

# see if we get a working hash:

self.assertTrue(check_password(password, conv))

# convert back and test with passlib:

back = self.converter.to_orig(conv)

self.assertEqual(orig, back)

网友答案:

Are Mixin classes AbstractBaseClasses? The most accurate answer for your case is no but it probably should be.

Your class as a stand-alone cannot survive for you reasons you pointed out. By making it an ABC you explicitly tell anyone looking at your class (like pycharm) that

from abc import ABCMeta, abstractmethod

class TestConverterMixin(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def assertEqual(self, other):
        "Need concrete implementation somewhere"

    .... the rest of your code 

The problem is that you would need this for all of the other methods (self.AssertTrue, self.converter etc). You could have something else in mind but this seriously looks like just a subclass of unittest.TestCase to me.

Oh and was PyCharm wrong. No, they got it right. If you made this an ABC or a subclass of TestCase, they would not have complained. If you used Interfaces, like zope.Interface, pycharm and the like usually get that wrong since they don't understand the registration and lookup process.(it is outside the python core)

相关阅读:
Top