簡體   English   中英

打點 function python

[英]Making Dot function python

是否可以制作一個點 function 即 var.function() 來更改 var? 我意識到我可以做到:

class Myclass:
   def function(x):
      return 2
Myclass.function(1):

但我想像默認的 python function 一樣更改它。

def function(x):
   return(3)
x=1
x.function()
print(x)

它返回

>>> 3
class Myclass:
  def __init__(self, num):
    self.num = num
  
  def function(self):
    self.num += 1

  def __str__(self):
    return str(self.num)

x = Myclass(3)
x.function()
print(x)

這是奇怪的用法。 我建議您創建自定義 class 來執行此操作,如果您不想在代碼中調用 function,請嘗試在其中使用 @property。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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