简体   繁体   English

Python:从 class 实例中访问变量的最佳方式?

[英]Python: Best way to access variable from within a class instance?

I've got a class named Player and there will be 200-300 instances of this class.我有一个名为Player的 class,这个 class 将有 200-300 个实例。 There is a function within this class called Move and this function requires knowledge of the map.在此 class 中有一个 function,称为Move ,此 function 需要了解 Z1D78DC8ED51214E9AEZ524B。

I also have a class named Map with 1-2 instances.我还有一个名为Map的 class 有 1-2 个实例。 What is the best way to feed an instance of Map into the Player instances?Map实例输入Player实例的最佳方法是什么?

I just ask because if i feed it to the instance upon Player init so I can access the instance via self.map - won't that be creating hundreds of copies of the Map instance (one for each instance of Player)?我只是问,因为如果我在 Player初始化时将它提供给实例,这样我就可以通过 self.map 访问该实例 - 这不会创建 Map 实例的数百个副本(每个 Player 实例一个)?

For all I know this could be the standard way of doing it but I have a nagging feeling that this isn't proper.据我所知,这可能是这样做的标准方式,但我有一种不合适的感觉。

Thanks谢谢

If you pass the Map to the Player at init this just passes a reference , not a copy.如果您在初始化时将Map传递给Player ,这只是传递了一个引用,而不是一个副本。 You will not create redundant instances of Map this way, and it's the best way to do it.您不会以这种方式创建Map的冗余实例,这是最好的方法。

Nothing in Python is ever implicitly copied. Python 中的任何内容都不会被隐式复制。 Whenever you do x = y , whether that's a function call or a variable/element/attribute assignment, x and y afterwards refer to the same object.每当您执行x = y时,无论是 function 调用还是变量/元素/属性赋值, xy之后都指的是同一个 object。

I see two pitfalls with your plan, though:不过,我发现您的计划存在两个缺陷:

  • Would the map also know about the players? map 是否也了解玩家? If so, you'll have a lot of circular references on your hands.如果是这样,你手上会有很多循环引用。 Just pass the map to move() , instead.只需将 map 传递给move()即可。
  • It seems more appropriate to have the map itself, or some other rich "game logic" class, handle the actual movement.让 map 本身或其他一些丰富的“游戏逻辑”class 来处理实际运动似乎更合适。 (I'm not a game dev, though; my gut instinct is just that a thing on a map shouldn't reach outside of itself and move itself around.) (不过,我不是游戏开发者;我的直觉是,map 上的东西不应该伸到自己外面并四处移动。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM