Class constructor able to init with an instance of the same class object

2024/11/16 1:08:20

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

I've tried this:

class Class(): def __init__(self,**kwargs):print selfself = kwargs.get('obj',self)print selfif not hasattr(self,'attr1'):print 'attr1'self.attr1  = kwargs.pop('attr1',[])if not hasattr(self,'attr2'):print 'attr2'self.attr2 = kwargs.pop('attr2',[])print selfself.attr1 = kwargs.pop('attr1',self.attr1)self.attr2 = kwargs.pop('attr2',self.attr2)print self.attr1print 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

The output is:

<__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]  []

But if I create a new instance with the instance inst:

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

The output is:

<__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:

    • "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

    • but "outside" the class:

    • inst2 has the address from the init and has no attributes!

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

Answer

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

    self = kwargs.get('object',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.attrxself.attry = other.attry# etc

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.

https://en.xdnf.cn/q/120319.html

Related Q&A

Python Logical Operators

I am currently learning Python3, but I dont understand Logical Operators. Here is the link: http://pymbook.readthedocs.org/en/py3/operatorsexpressions.html#logical-operators First of all, it seems that…

Partial Pivoting In Pandas SQL Or Spark

Partial Pivoting In Pandas SQL Or Spark Make the Year remain as Rows, and have the States Transpose to columns Take Pecentage value of a Gender Male Race White, InputOutput

Python to create a find-replace dictionary from a word vba macro

I have a very big macro Selection.Find.ClearFormattingSelection.Find.Replacement.ClearFormattingWith Selection.Find.Text = "asa".Replacement.Text = "fsa".Forward = True.Wrap = wdFin…

Converting many .txt files into csv and combining them

I have many .txt files. I want to convert a few files ending with specific names into csv and combine them into one csv. ### Folder Name: text_files python_gramm.py aadd01.txt aaxx02.txt aaff03.txt hhd…

Calculation between two columns in Python?

When I tried to do some calculation between two columns (like division), I get an error: column_ratio[x]=(float(column1[y]))/(float(column2[z])) TypeError: tuple indices must be integers, not str. C…

Why does input() always return a string?

Here is my code:age = input("How old are you?: ") print (age) print (type(age))Result:How old are you?: 3535class str <<--- This is problem!But, If I use.. age = int(input("How …

Windowed mode cannot run

Why does pyinstaller exe not run in windowed mode but fine without it? I have changed over to a windows OS from Linux. Never had any issue before hand, how do I correct this.

inserting a variable into an fstring using .replace()

I have a code something similar to bellow. name = Dave message = f<name> is a really great guy! message = message.replace(<name>, {name}) print(message)the variables are a little more compl…

How to allow caps in this input box program for pygame?

I found this input box module on the internet but it only allows lower case no upper. So could someone tell me what to change in the module to allow caps as im creating a small multiplayer game and i n…

Why testing error rate increases at high values of K in KNN algorithm?

I am getting the error rates like this up to 20 values what might be the reason for this ?k_values: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Error [0.0, 0.0, 0.0, 0.0, 0…