Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

python - Is it bad practice to modify a reference inside a method, rather than returning values?

Let's say I have:

Class Player():
    
    def makeAction():
        # modify state

Class State():
    
   def __init___(self):
      self.x = 'x'
      self.y = 'y'

Class GameEngine():
   
    def __init__(self):
        self.players = []
        self.state = State()
  
    def makeActions():
        for player in self.players:
            player.makeAction(self.state)

My issue is that the code for my game is already pretty large, and it seems like it would be easier to follow if it were more obvious exactly where the state gets updated. There are three things I can think of to change this: change the last line to something like

  1. self.state = player.makeAction(self.state)
  2. self.state = player.makeAction(copy(self.state))
  3. self.state.x, self.state.y = player.makeAction(self.state.x, self.state.y)

Option 1 is superfluous but seems to make the code more clear, 2 just looks ugly. Option 3 seems the "cleanest" but may get hard to read if I'm passing in and retrieving lots of attributes. I could also keep it as is.

question from:https://stackoverflow.com/questions/65622791/is-it-bad-practice-to-modify-a-reference-inside-a-method-rather-than-returning

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...