簡體   English   中英

從Python 2.7中的另一個類方法調用一個類方法

[英]Calling a class method from another class method in Python 2.7

我很困惑為什么這段代碼行不通。 對於room_instance = self.startRoom()我得到了錯誤:

'str' object is not callable.  

我的代碼:

class Corridor:
    def enter(self):
        print "Yureka. First Room!"

class Engine(object):
    def __init__(self, startRoom):
        self.startRoom = startRoom   #sets the startRoom to 'Corridor' for the eng instance
    def room_change(self):
        room_instance = self.startRoom()
        room_instance.enter()

eng = Engine('Corridor')
eng.room_change()

當您使用eng = Engine('Corridor') ,會將'Corridor'作為字符串傳遞。 要訪問類走廊,您應該使用globals()['Corridor']

class Engine(object):
    def __init__(self, startRoom):
        self.startRoom = globals()[startRoom]   #sets the startRoom to 'Corridor' for the eng instance

    def room_change(self):
        room_instance = self.startRoom()
        room_instance.enter()

但這實際上是一個相當脆弱的構造,因為可能在其他模塊等中定義了Corridor 。因此,我提出以下建議:

class Corridor:
    def enter(self):
        print "Yureka. First Room!"

class Engine(object):
    def __init__(self, startRoom):
        self.startRoom = startRoom   #sets the startRoom to 'Corridor' for the eng instance
    def room_change(self):
        room_instance = self.startRoom()
        room_instance.enter()

eng = Engine(Corridor) # Here you refer to _class_ Corridor and may refer to any class in any module
eng.room_change()

暫無
暫無

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

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