我在棋盘游戏Battleship上做了一个项目。因为0,1,2,3 ...是1,2,3,4 ......(我不知道该怎么称呼它),我需要变量行和列比它们小一点,即:
row -= 1
column -= 1
我需要在一堆函数中使用它,所以我认为如果我每次只有一个辅助函数它会更整洁。我尝试过这两种方法:
row, column = row -= 1, column -= 1
但是,这给我column -= 1
上的语法错误。
我也尝试过:
def decimal_helper(row, column):
row -= 1
column -= 1
return row, column
但是,这只会返回一个元组,而我需要单独返回两个变量。
答案 0 :(得分:2)
row, column = row - 1, column - 1
你也可以采用更优雅的方式,并使用@jonrsharpe建议的单行:
An exception of type 'System.IO.IOException' occurred in Npgsql.dll but was not handled in user code
Additional information: TlsClientStream.ClientAlertException: CertificateExpired
at TlsClientStream.TlsClientStream.SendAlertFatal(AlertDescription description, String message)
at TlsClientStream.TlsClientStream.ParseCertificateMessage(Byte[] buf, Int32& pos)
at TlsClientStream.TlsClientStream.TraverseHandshakeMessages()
at TlsClientStream.TlsClientStream.GetInitialHandshakeMessages(Boolean allowApplicationData)
at TlsClientStream.TlsClientStream.PerformInitialHandshake(String hostName, X509CertificateCollection clientCertificates, RemoteCertificateValidationCallback remoteCertificateValidationCallback, Boolean checkCertificateRevocation)
答案 1 :(得分:0)
我发现这更优雅。这样就封装了“转换”逻辑,不需要在整个代码中复制它:
class DecimalHelper:
def __init__(self, row, column):
self.row = row
self.column = column
self.rowIndex = row - 1
self.colIndex = column - 1
row = 3
column = 4
dc = DecimalHelper(row, column)
print dc.rowIndex
print dc.colIndex
还有一种更优雅的方式,使用类属性(this帖子的信用):
class ClassPropertyDescriptor(object):
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
return self.fget.__get__(obj, klass)()
def __set__(self, obj, value):
if not self.fset:
raise AttributeError("can't set attribute")
type_ = type(obj)
return self.fset.__get__(obj, type_)(value)
def setter(self, func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
self.fset = func
return self
def classproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return ClassPropertyDescriptor(func)
class DecimalHelper:
def __init__(self, row, column):
self.row = row
self.column = column
@classproperty
def rowIndex(cls):
return row - 1
@classproperty
def colIndex(cls):
return column - 1
row = 3
column = 4
dc = DecimalHelper(row, column)
print dc.rowIndex
print dc.colIndex