[英]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 调用还是变量/元素/属性赋值, x
和y
之后都指的是同一个 object。
I see two pitfalls with your plan, though:不过,我发现您的计划存在两个缺陷:
move()
, instead.move()
即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.