【发布时间】:2018-09-05 20:49:24
【问题描述】:
我正在尝试创建一个语法友好的库,它不需要用户不断地传递凭据或键入多余或过多的语句。我的策略是专注于我希望库语法的外观,然后设计库以这种方式运行。我知道我可以实现以下内容:
api = Api(user="admin", pswd="blahblah")
new_order = api.Order()
new_order.status = "pending"
api.create(new_order)
api.order_assign_user(new_order, user)
existing_order = api.get_order(orderId=12345)
existing_order.status = "shipped"
api.update(existing_order)
使用类似下面的东西:
class Api(object):
def __init__(self, user=None, pswd=None):
self.user = user
self.pswd = pswd
class Order(api):
def __init__ (self, status=None):
self.status = status
def create(self, x):
auth = Auth(self.user, self.pswd)
# use authorization credentials to create data remotely
return x
def update(self, x):
auth = Auth(self.user, self.pswd)
# use authorization credentials to update data from remote
return x
def get_order(self, orderId=None):
auth = Auth(self.user, self.pswd)
# use authorization credentials to update data from remote
return order
但我希望能够使用以下语句:
new_order.create() # instead of api.create(new_order)
new_order.assign_user(user) # instead of api.order_assign_user(new_order, user)
existing_order = api.Order.get(orderId=12345) # returns retrieved Order Instance
这给我带来了一个问题:
如何让Order() 实例访问创建它的Api() 实例的属性?如果无法访问这些,任何属性(如“user”和“pswd”)都将无法访问(requests.get() 调用需要它们)
我尝试了各种函数和类来完成此任务,但始终无法解决此问题。这是我能做到的最接近的:
class Api(object):
def __init__(self, user=None, pswd=None):
self.user = user
self.pswd = pswd
class Order(api):
def __init__ (self, status=None):
self.status = status
@classmethod
def get(cls, value):
return cls(status=value)
def create(self):
auth = Auth(self.user, self.pswd)
# these credentials need to come from the Api() instance?, not self
return x
def update(self):
auth = Auth(self.user, self.pswd)
# these credentials need to come from the Api() instance?, not self
return x
这可能吗?还是我以错误的方式解决这个问题?我考虑过把它做成一个模块,但这似乎也不是一个有效的选择。
【问题讨论】:
-
有可能,但我现在没时间给出正确的答案,如果还没有人发帖我会回来回答,同时看看
__get__和@ 987654328@ 魔术方法以及它们如何接收instance参数,您可以在Api类中实例化您的Order类并利用这些方法
标签: python python-3.x inner-classes