Python 重写导入类中的特定方法
我正在构建一个可以玩几个纸牌游戏的应用程序。在最底层,我有一个卡片类,每个游戏类都会导入它,见下文Python 重写导入类中的特定方法,python,Python,我正在构建一个可以玩几个纸牌游戏的应用程序。在最底层,我有一个卡片类,每个游戏类都会导入它,见下文 class Card: def __init__(self, rank=None, suit=None): ranks = {'2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'} suits = {'Spades', 'Diamonds', 'Clubs', 'Hearts'}
class Card:
def __init__(self, rank=None, suit=None):
ranks = {'2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'}
suits = {'Spades', 'Diamonds', 'Clubs', 'Hearts'}
assert(rank in ranks), 'Not a valid rank'
assert(suit in suits), 'Not a valid suit'
self.rank = rank
self.suit = suit
@staticmethod
def rank_to_numeric(rank):
if rank == 'J':
return 11
if rank == 'Q':
return 12
if rank == 'K':
return 13
if rank == 'A':
return 14
else:
return int(rank)
def __repr__(self):
return f'{self.rank} of {self.suit}' # Example: 7 of Spades
def __lt__(self, other):
return self.rank_to_numeric(self.rank) < self.rank_to_numeric(other.rank)
def __le__(self, other):
return self.rank_to_numeric(self.rank) <= self.rank_to_numeric(other.rank)
def __eq__(self, other):
return (self.rank, self.suit) == (other.rank, other.suit)
def __ne__(self, other):
return not (self == other)
def __gt__(self, other):
return self.rank_to_numeric(self.rank) > self.rank_to_numeric(other.rank)
def __ge__(self, other):
return self.rank_to_numeric(self.rank) >= self.rank_to_numeric(other.rank)
是的,你可以这样做:
class A:
def foo(self):
print("foo")
class B:
def new_foo(self):
print("new_foo")
def over_ride(self):
A.foo = self.new_foo
def __init__(self):
self.over_ride()
这将重新分配A
类的foo
。如果您将从代码中的任何位置访问A
,则从您创建B
实例的那一刻起,它将拥有new_foo
的主体
在你的情况下,会是这样的
class Toepen:
"""
class for the popular dutch card game Toepen.
Rules according wikipedia: https://nl.wikipedia.org/wiki/Toepen
The optional rules can be set in the settings
"""
def __init__(self):
# Set the round counter. A single game consists of 4 rounds
self.round = 0
Card.__lt__ = self.new__lt__
# Set the trump (troef)
self.trump = None
# Set the highest card played so far
self.incumbent = 0
# Set the pile of cards so far played in this round
self.pile = []
def new__lt__(self,other):
pass
class Toepen:
"""
class for the popular dutch card game Toepen.
Rules according wikipedia: https://nl.wikipedia.org/wiki/Toepen
The optional rules can be set in the settings
"""
def __init__(self):
# Set the round counter. A single game consists of 4 rounds
self.round = 0
Card.__lt__ = self.new__lt__
# Set the trump (troef)
self.trump = None
# Set the highest card played so far
self.incumbent = 0
# Set the pile of cards so far played in this round
self.pile = []
def new__lt__(self,other):
pass