簡體   English   中英

有沒有一種方法可以從Python中的兩個不同對象訪問同一對象?

[英]Is there a way to access the same object from two different objects in Python?

我一直在嘗試通過制作紙牌游戲來練習python類。 簡而言之,人類玩家可以從同一副牌上玩計算機。 我的問題是如何使人類玩家和計算機訪問同一卡座?

我創建了一個Player類,一個Computer類和一個Deck類。 播放器類和計算機類都是Deck類固有的。 在Deck類中,我有一個用於“ deck”的類變量。 但是我注意到的是,如果將Deck方法應用於“ deck”類變量,然后將其作為播放器實例調用,則對“ deck”類變量的任何更改都將綁定到播放器實例,因此計算機實例將無法訪問它。

也許我錯過了一些東西,或者我打算徹底犯錯,有人可以提供一些輸入嗎?

播放器類和計算機類都是Deck類固有的

那不是理想的方法。 僅當兩個類在概念上滿足“是”關系時,才應從另一個類繼承。 例如,狗應從動物繼承,因為狗是動物。 玩家不應從Deck繼承,因為玩家不是牌組。

而不是繼承,請嘗試使套牌成為播放器和計算機對象的屬性。 如果deck對象是可變的,則對這兩個對象的更改都將可見。

class Deck:
    def __init__(self):
        self.cards = ["Pot of Greed", "Black Lotus", "Ace of Spades", "Draw Four"]

class Player:
    def __init__(self, name, deck):
        self.name = name
        self.deck = deck

class Computer:
    def __init__(self, difficulty, deck):
        self.difficulty = difficulty
        self.deck = deck

d = Deck()
p = Player("Steve", d)
c = Computer("Easy", d)

#confirm that the player and computer decks are the same object
print(p.deck is c.deck)

#changes made to the deck via p will be observable from c and vice versa
p.deck.cards.append("How to Play Poker Instruction Card")
print(c.deck.cards)

暫無
暫無

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

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