简体   繁体   中英

Zope.interface in Django

I am from a Java background and now working on a django application. Need your input if I am in the wrong direction.

I am trying to implement zope.interface.Interface in my Django application and trying to achieve what interfaces in Java do, but it does not throw any error if the implementer class does not provide the definition of all the methods in the interface.

Here is my sample implementation.

import zope.interface

class MyInterface(zope.interface.Interface):
    x = zope.interface.Attribute("foo")
    def method1(self, x):
        pass
    def method2(self):
        pass
  
@zope.interface.implementer(MyInterface)
class MyClass:
    def method1(self, x):
        return x**2
    def method2(self):
        return "foo"

@zope.interface.implementer(MyInterface)
class MyClass2:
    def method1(self, x):
        return x**2

print(list(zope.interface.implementedBy(MyClass)))
print(list(zope.interface.implementedBy(MyClass2)))

c = MyClass()
print(c.method1(5))
print(c.method2())

d = MyClass2()
print(d.method1(5))

Kindly help me find out what am I doing wrong and your kind guidance.

Thank you,

I am going with MetaClass instead of Zope Interface. Here is the solution

class IStudent(type):

    def __new__(cls, name, bases, attrs):
        print("New from Interface")
        x = super().__new__(cls, name, bases, attrs)
        
        # Functions to be implemented
        if(not hasattr(x, 'test')):
            x.test = lambda self: print("Method not implemented")
        
        return x
        
class Student1(metaclass=IStudent):
    def __init__(self):
        print("Init from Student1")

class Student2(metaclass=IStudent):
    def __init__(self):
        print("Init from Student2")
    
    def test(self):
        print("This is implemented method from Student 2")


std1 = Student1()
std2 = Student2()
std1.test()
std2.test()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM