簡體   English   中英

如何定義一個函數,以便可以在對象上調用它?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM