可以使用同一类对象的实例初始化的类构造函数 [英] Class constructor able to init with an instance of the same class object

查看:100
本文介绍了可以使用同一类对象的实例初始化的类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python可以创建一个可以使用同一类对象的实例初始化的类吗?

Can python create a class that can be initialised with an instance of the same class object?

我已经尝试过:

class Class(): 

    def __init__(self,**kwargs):

        print self

        self = kwargs.get('obj',self)

        print self

        if not hasattr(self,'attr1'):
            print 'attr1'
            self.attr1  = kwargs.pop('attr1',[])
        if not hasattr(self,'attr2'):
            print 'attr2'
            self.attr2 = kwargs.pop('attr2',[])

        print self

        self.attr1 = kwargs.pop('attr1',self.attr1)
        self.attr2 = kwargs.pop('attr2',self.attr2)
        print self.attr1
        print self.attr2

如果创建新实例,则没有问题:

If I create a new instance there is no problem:

inst = Class(attr1=[1,2,3])
print inst
print inst.attr1,inst.attr2

输出为:

<__main__.Class instance at 0x7f2025834cf8>  
<__main__.Class instance at 0x7f2025834cf8>  
attr1  
attr2  
<__main__.Class instance at 0x7f2025834cf8>  
[1, 2, 3]  
[]  
<__main__.Class instance at 0x7f2025834cf8>  
[1, 2, 3]  []

但是如果我使用实例 inst

inst2 = Class(obj=inst)
print inst2
print inst2.attr1,inst2.attr2

输出为:

<__main__.Class instance at 0x7f202584b7e8>  
<__main__.Class instance at 0x7f2025835830>  
<__main__.Class instance at 0x7f2025835830>  
[1, 2, 3]  
[]  
 <__main__.Class instance at 0x7f202584b7e8>  







AttributeError                            Traceback (most recent call last)  
<ipython-input-228-29c9869a9f4d> in <module>()  
       1 inst2 = Class(obj=inst)  
       2 print inst2  
 ----> 3 print inst2.attr1,inst2.attr2  

 AttributeError: Class instance has no attribute 'attr1'  

我处理了这个问题,但我不知道如何解决:

I handle the problem but i dont know how to solve it:


  • 在第一种情况下,实例地址始终是

  • 在第二种情况下:

  • in the 1st case the instance address is always the same ("inside" and "outside" the class)
  • in the 2nd case:


  • 在类内部:

  • init调用在新地址处创建新实例

  • 然后将self设置为上一个实例和更改地址:确定

  • self 已经具有属性 attr1 atrr2 :确定

  • "inside" the class:
  • the init call create a new instance at a new address
  • then self is set to the previous instance and change address: OK
  • self already has attributes attr1 and atrr2 : OK

但在类之外:

怎么了?地址情感在Python中如何工作?
是这样做的好方法吗?

What is wrong ? How does address affectation work in Python? Is it a good manner of doing this?

推荐答案

不确定您要实现的目标,但从技术上讲您的错误在这里:

Not sure what you're trying to achieve, but technically your error is here:

    self = kwargs.get('object',self)

本身并没有什么神奇之处,它只是一个函数参数,因此,变量,因此在函数中重新绑定它只会使本地名称 self 指向函数范围内的另一个对象 。这绝不会影响当前实例(通过包装方法传递给 __ init __ 的那个实例),它只会使 self 对象的别名。

There's nothing magic with self, it's just a function argument, and as such a local variable, so rebinding it within the function will only make the local name self points to another object within the function's scope. It's in no way affecting the current instance (the one that was passed to __init__ by the method wrapper), it just makes self an alias for object.

如果要复制中的属性对象自己,则必须明确地做到这一点:

If what you want is to copy attributes from object to self, you have to do it explicitly:

 other = kwargs.get('object')
 if other is not None:
     self.attrx = other.attrx
     self.attry = other.attry
     # etc

哦,是的:Python是高级语言,没有像地址影响之类的东西-您所拥有的只是引用对象的名称(实际上是name => object mapping)。名称只是名称,对象的实际居住地与您无关。

Oh and yes: Python is high-level language, there's nothing like "address affectation" - all you have are names refering to objects (really, name=>object mapping). A name is just a name, and where the object actually lives is none of your concerns.

这篇关于可以使用同一类对象的实例初始化的类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆