Python-如果未定义子对象,则使类返回对象

时间:2018-12-05 20:42:10

标签: python class

我不确定Python是否允许类似我想要实现的功能。基本上,我试图为一个类分配一个默认对象,以便如果直接引用该类,它将返回该对象,否则它将访问该类的子对象。

这就是我要在代码中实现的目标:

>>> class MyClass(object):
...     a = 0
...     b = 1
...     def __new__(cls):
...         return 2

>>> obj = MyClass()

>>> # I want it to print 0
>>> print obj.a
AttributeError: 'int' object has no attribute 'a'

>>> # I want it to print 1
>>> print obj.b
AttributeError: 'int' object has no attribute 'b'

>>> # I want it to print 2
>>> print obj
2

1 个答案:

答案 0 :(得分:1)

您可以改为int的子类:

class MyClass(int):
    a = 0
    b = 1
    def __new__(cls, value):
        return super(MyClass, cls).__new__(cls, value)

这样:

obj = MyClass(2)
print(obj.a)
print(obj.b)
print(obj)

输出:

0
1
2