简体   繁体   English

Django 中的 Zope.interface

[英]Zope.interface in Django

I am from a Java background and now working on a django application.我来自 Java 背景,现在正在开发 django 应用程序。 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.我正在尝试在我的 Django 应用程序中实现 zope.interface.Interface 并尝试实现 Java 中的接口所做的事情,但是如果实现者类没有提供接口中所有方法的定义,它不会抛出任何错误。

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.我将使用 MetaClass 而不是 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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