我正在创建一个名为Conversation的类作为更大代码的一部分,并希望确保用户输入的字段是有效的(如果它们无效则我想提出值错误),但是当我运行程序时,我的is_valid方法不起作用:
课堂对话:
def __init__(self, members, size_limit, backup_policy, cloud_account_prefix='./'):
if not self.is_valid():
raise ValueError
self.members = members
self.size_limit = size_limit
self.backup_policy = backup_policy
self.cloud_account_prefix = cloud_account_prefix
self.backup_count = 0
self.size_count = 0
self.messages = []
def is_valid(self, members, size_limit, backup_policy, cloud_account_prefix):
if self.members < 2:
return False
if self.size_limit <= 10:
return False
if not path_ok(self.cloud_account_prefix):
return False
if self.backup_policy < 1:
return False
else:
return True
我做错了什么?
答案 0 :(得分:2)
在进行任何初始化之前,您正在调用is_valid
,因此对self.something
内的AttribueError
进行任何调用都会产生is_valid
。
class Conversation:
def __init__(self, members, size_limit, backup_policy, cloud_account_prefix='./'):
self.members = members
self.size_limit = size_limit
self.backup_policy = backup_policy
self.cloud_account_prefix = cloud_account_prefix
self.backup_count = 0
self.size_count = 0
self.messages = []
if not self.is_valid():
raise ValueError
def is_valid(self):
if self.members < 2:
return False
if self.size_limit <= 10:
return False
if not path_ok(self.cloud_account_prefix):
return False
if self.backup_policy < 1:
return False
else:
return True
需要4个参数,你用0来称呼它。
您的代码应为
__init__
另一种方法可能是将所有参数从is_valid
传递给class Conversation:
def __init__(self, members, size_limit, backup_policy, cloud_account_prefix='./'):
if not self.is_valid(members, size_limit, backup_policy, cloud_account_prefix):
raise ValueError
self.members = members
self.size_limit = size_limit
self.backup_policy = backup_policy
self.cloud_account_prefix = cloud_account_prefix
self.backup_count = 0
self.size_count = 0
self.messages = []
def is_valid(self, members, size_limit, backup_policy, cloud_account_prefix):
if members < 2:
return False
if size_limit <= 10:
return False
if not path_ok(cloud_account_prefix):
return False
if backup_policy < 1:
return False
else:
return True
,以便在开始初始化实例属性之前验证它们是否有效:
//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]