[英]How can I define a function in django so that stays active in background?
[英]How to define a function so it can be called on the object?
我想做一个像这样的函数定义:
def x(a, b):
#do stuff
但是以这种方式使它可以调用:
num1=1
num2=2
num1.x(num2)
有没有办法做到这一点?
不,你想要的只能用Python中的方法来实现。 它不像C ++,你可以在课堂外定义“非成员”方法(我不确定这是否是这些的名称,但我希望你知道我的意思)。
Pythons整数(还有浮点数,字符串等)也不支持新的属性/方法,所以实现这一点的唯一方法是实际上对类进行子类化或创建一个新类:
class MyClass(object): # a custom class
def __init__(self, val):
self.val = val
def x(self, other):
return self.__class__(self.val + other.val)
def __repr__(self):
return '{self.__class__.__name__}({self.val})'.format(self=self)
>>> n1 = MyClass(1)
>>> n2 = MyClass(2)
>>> n1.x(n2)
MyClass(3)
你不能这样做添加方法。 你也可以使用下面的一个:
def x(a, b):
num = a + b
return num
x = x(1,2)
print(x)
为什么不使用类并在类中定义名为add的方法。
一个简单的实现:
>>> class integer(int):
... def __init__(self,n) :
... self.num = n
... def add(self,m) :
... return self.num+m
...
>>> num1 = 1
>>> num2 = 2
>>> num1 + num2
3
>>> num1 = integer(num1)
>>> num1.add(num2)
3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.