我很难总结我的问题,所以如果这是重复,我会道歉。
我有一个类似的课程:
class MyClass:
timer = 60
我希望timer
表示一个整数,但也扩展了一些自定义方法。例如:
>>> c = MyClass()
>>> c.timer
60
>>> c.timer.wait() # This would wait 60 seconds
True
>>> c.timer
0
我怎样才能在Python中执行此操作?
答案 0 :(得分:0)
不确定您要实现的目标,但您的MyClass可以按如下方式实现:
class MyClass:
def __init__(self):
self.a = 0
self.b = 0
def do_some_operation(self):
# do something using a and b
# and return True if success
self.a += 100;
return True
c = MyClass()
print(c.do_some_operation()) # True
print(c.a) # 100
答案 1 :(得分:0)
也许你应该尝试创建一个模拟整数的类:
class Integer:
value = 0
def __init__(self, value):
self.value = value
def __add__(self, other):
return Integer(self.value + other.value)
#Would need to do the other basic arithmetic things. I'll leave that to you...
def __str__(self):
return str(self.value)
def do_some_operation(self):
return True
class MyClass:
a = Integer(0)
b = Integer(0)
c = MyClass()
print c.a
print c.b
print c.a + c.b
print c.a.do_some_operation()
给出:
0
0
0
True
虽然这样做我会小心。可能还有另一种更合适的方式。