【发布时间】:2017-06-05 20:07:34
【问题描述】:
在 Python 3.6 中,假设我有一个抽象类 MyAbstractClass
from abc import ABC, abstractmethod
class MyAbstractClass(ABC):
@property
@abstractmethod
def myProperty(self):
pass
还有一个类MyInstantiatableClass 继承自它。那么如何在从此类中实例化对象时写入属性myProperty?我希望能够设置和获取myProperty。下面不行。
from MyAbstractClass import MyAbstractClass
class MyInstantiatableClass(MyAbstractClass):
def __init__(self, desiredValueOfMyProperty):
????
@myProperty.setter
def myProperty(self, desiredValueOfMyProperty): # value coming from __init__
self._myProperty = desiredValueOfMyProperty
还有一个主要功能,比如说,
from MyInstantiatableClass import MyInstantiatableClass
def main():
MyInstantiatableClass(3) # 3 is the desiredValueOfMyProperty for this instantiation
MyInstantiatableClass(5) # 5 is the desiredValueOfMyProperty for this instantiation
【问题讨论】:
-
你是在实现only setter,没有getter吗?
-
我希望能够在
MyInstantiatableClass设置和获取myProperty。 -
以与通常相同的方式定义属性。
标签: python python-3.x inheritance abstract-class