[英]Python access to object as a function (not __call__)
I want to do the following: I have a container-class Container, it has attribute attr, which refers to another class OtherClass. 我要执行以下操作:我有一个容器类的Container,它具有属性attr,它引用另一个类OtherClass。
class OtherClass:
def __init__(self, value):
self._value = value
def default(self):
retirn self._value
def another(self):
return self._value ** 2
def as_str(self):
return 'String: %s' % self._value
class Container:
def __init__(self, attr):
self.attr = OtherClass(attr)
I want to: 我想要:
x = Container(2)
x.attr # when accessing the attribute - return value from default method
2
x.attr.another() # but also an attribute can be treated as an object
4
x.attr.as_str()
'String: 2'
How can I do this? 我怎样才能做到这一点?
Not sure if this is what you need. 不知道这是否是您所需要的。 Seems like an odd design to me 对我来说似乎是一个奇怪的设计
>>> class OtherClass(int):
... def __init__(self, value):
... self._value = value
... def another(self):
... return self._value ** 2
...
>>> class Container:
... def __init__(self, attr):
... self.attr = OtherClass(attr)
...
>>> x=Container(2)
>>> x.attr
2
>>> x.attr.another()
4
just-because-you-use-classes-doesn't-mean-it's-OO-ly gnibbler 只是因为您使用课程并不意味着它只是一种ly头
除非OtherClass
重写__int__()
,然后将其放入int()
以获取整数值,否则您不能这样做。
What is attr
meant to be? attr
是什么意思? You can't have it both ways; 不能同时拥有它。 either it's the return value of some function or it's an instance of OtherClass
. 它是某个函数的返回值,或者是OtherClass
的实例。
How about making OtherClass
inherit from Integer
? 如何使OtherClass
从Integer
继承?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.