2013-04-13 22 views
0

有没有办法从第一类到第二类获取局部变量?第一类到第二类的局部变量

class Position: 
    positionX = 0.0 #starting value of positionX, but I need to change this in counting method when I push arrow key 

    def counting(self, posX): 
     self.positionX = posX #posX is for example position X of my cursor which I move with arrows so value is changing when I push to arrow key. 

class Draw: 
    posInst = Position() 
    print posInst.positionX #here I need to get positionX variable from Position class. But its show me just 0.0. I need to get exact value which is change when I push arrow key and its change in counting method. If I push arrow key and value in counting method will be 20 I need this number in Draw class. But everytime is there 0.0. 

有什么办法可以做到这一点?感谢您的建议。

回答

1

,在你的代码所示线

print posInst.positionX 

打印0.0的原因是因为绘制创建自己的,你有没有叫其计数方法来改变它的位置的实例。

class Position: 
    positionX = 0.0 

    def counting(self, posX): 
     self.positionX = posX 


class Draw: 
    posInst = Position() 
    posInst.counting(20) 
    print posInst.positionX 

draw = Draw() 

在您的实际代码中,Draw类实际上是自己创建Position类的实例。

如果是那么当你想调用你的draw_instance.posInst.counting(value)。

如果你正在创建一个你想直接调用它的计数方法的单独的头寸实例,那么你最好传入来绘制头寸实例。

0

执行此操作的“正确”方法是在您的Position类中包含get方法,该方法返回positionX。直接访问其他类内部变量被认为是不好的做法。

class Position: 
    positionX = 0.0 

    def counting(self, posX): 
     self.positionX = posX 

    def getPosition(self): 
     return self.positionX 

class Draw: 
    posInst = Position() 
    print posInst.getPosition() 
+0

Noes。 Python讨厌冗长,getter不可能成为Python中任何东西的“正确”方式。 – bobrobbob

+0

我想你会发现,虽然更详细,但所有的内部变量都应该受到保护而不受外部操纵。这是针对任何OOP语言中的任何对象,任何更改都应通过函数调用进行,而不是直接进行 – TheMerovingian

+0

我找到了解决方案。当我在Position类的构造函数__init__中使用它的工作。但它只在mainLoop中工作。 – Thomas

0

所以它的工作方式如此。

class Position: 
    def __init__(self): 
     self.positionX = 0.0 

    def counting(self, posX): 
     self.positionX = posX 

def mainLoop: 
    position = Position() 

    while running: 
     position.positionX 

我在另一个类中尝试这个,但它只是在循环中工作。但它的工作。感谢所有的建议:)