如何在python中使用abstractproperty装饰器强制子类设置属性? [英] How to enforce a child class to set attributes using abstractproperty decorator in python?

查看:775
本文介绍了如何在python中使用abstractproperty装饰器强制子类设置属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想强制执行一个Child类来设置几个属性(实例变量),以实现我在python 2.7中使用abstractproperty装饰器。以下是示例代码:

I want to enforce a Child class to set several attributes(instance variables), to achieve I am using abstractproperty decorator in python 2.7. Here is the sample code:

from abc import ABCMeta, abstractproperty
class Parent(object):
    __metaclass__ = ABCMeta
    @abstractproperty
    def name(self):
        pass

class Child1(Parent):
    pass

class Child2(Parent):
    name = 'test'

class Child3(Parent):
    def __init__(self):
        self.name = 'test'

obj_child1 = Child1()

Child1对象创建会产生错误,因为

Child1 object creation gives an error as expected.

obj_child2 = Child2()

Child2对象的创建工作正常,因为设置了抽象属性'name'

Child2 object creation works fine as because abstract attribute 'name' is set

但是

 obj_child3 = Child3()

给予 TypeError:无法使用抽象方法名称实例化抽象类Child3

我不明白:尽管在 init
方法,为什么Child3对象创建会引发类型错误。

I did not understand:although the attribute 'name' is set in the init method, why the Child3 object creation is throwing type error.

我的要求是在子类的方法内设置属性。解释child2类有什么问题以及是否有更好的方法来强制子类在方法中设置属性将对我有所帮助。

My requirement is set attributes inside a method of child class. An explanation of what is wrong with child2 class and if there is a better way to enforce a child class to set attributes in a method will help me. Thanks in advance.

推荐答案

您可以这样做,
父类:

You can do some like this, parent class:

class Parent(object):
    __metaclass__ = ABCMeta
    @abstractproperty
   def name(self):
       pass

儿童班:

class Child(Parent):
    name = None
    def __init__(self):
        self.name = 'test'

现在

obj = Child()
obj.name

给出所需的测试输出。

这样,您可以强制一个类设置父类的属性,而在子类中可以从方法中设置它们。
这不是您需要的完美解决方案,但是很接近。此解决方案的唯一问题是,您将需要在子类中将父对象的所有抽象属性定义为 None ,并使用方法对其进行设置。

By doing this you can enforce a class to set an attribute of parent class and in child class you can set them from a method. It is not a perfect solution that you require, but it is close. The only problem with this solution is you will need to define all the abstractproperty of parent as None in child class and them set them using a method.

这篇关于如何在python中使用abstractproperty装饰器强制子类设置属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆