[英]How to name method used by __init__ to determine value of new object?
I'm new to Python, I started learning Python3.3 few days ago. 我是Python的新手,几天前我开始学习Python3.3。
Let's have 2 classes, Source
and Dest
; 让我们有两个类,
Source
和Dest
; Dest
is declared before Source
. Dest
在Source
之前声明。
I'd like to make a object belonging to class Dest
with content according to on object belonging to class Source
. 我想根据属于
Source
类的on对象来使一个属于Dest
类的对象具有内容。
If it was C++ (which I know quite well), to do thas I could allow casting Source
to Dest
by writing Source::operator Dest()
, operator Dest(Source)
, Dest::Dest(Source)
, operator Dest(Source&)
or Dest::Dest(Source&)
. 如果是C ++(我知道得很好),做全髋关节置换,我可以让铸造
Source
到Dest
通过编写Source::operator Dest()
operator Dest(Source)
, Dest::Dest(Source)
, operator Dest(Source&)
或Dest::Dest(Source&)
。
I think about decorating Dest
's __init__
to set Dest
's object's value on value returned by passed argument's special_method (if exist), which should return object with attributes similar to Dest
's object. 我考虑装饰
Dest
的__init__
以将Dest
的对象的值设置为传递的参数的special_method (如果存在)返回的值,该参数应返回具有与Dest
的对象相似的属性的对象。
In code it could look like that: 在代码中可能看起来像这样:
def allow_conversion(prev_init, special_method_name):
def wrap(self, source, *args, **dic):
try:
#call getattr(source, special_method_name)(*args, **dic)
#copy attributes of returned object (don't know how to implement)
except Exception: #if getattr(source, special_method_name)
pass #doesn't exist or raised Exception
finally:
prev_init(source, *args, **dic) #original __init__ is always called
return wrap
class Dest:
@allow_conversion('special_method')
def __init__(self):
pass #do some initializing
I wonder how to name the special_method . 我不知道如何命名special_method 。 Is there any habit?
有什么习惯吗?
If I understand your question correctly, you simply want to create an instance of Dest
using an instance of Source
. 如果我正确理解了您的问题,则只想使用
Source
的实例创建Dest
的实例。 For that, you should define a class method in Dest
which takes an instance of Source
as an argument, and returns a properly initialized instance of Dest
. 为此,您应该在
Dest
定义一个类方法,该方法将Source
的实例作为参数,并返回正确初始化的Dest
实例。
class Source:
def __init__(self, x, y):
self.x = x
self.y = y
class Dest:
def __init__(self, a):
self.a = a
@classmethod
def from_source(cls, src):
return Dest(src.x + src.y)
s = Source(5, 3)
d = Dest.from_source(s)
assert d.a == 8
All the logic for "converting" an instance of Source
to an instance of Dest
will reside in Dest.from_source
. 用于将
Source
实例“转换”为Dest
实例的所有逻辑都将驻留在Dest.from_source
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.