fruitegg fruitegg - 15 days ago 5
Python Question

How to Manipulate an Attribute in a Class from a Method in a Separate Class python

Suppose I have the following:

class A:

def __init__( self, Att):
"""here Att is a string input"""
self.Att = Att

def __repr__( self ):
s = "My attribute is " + self.Att
return s

class B:

def __init__( self, Btt):
"""here Btt is a string input"""
self.Btt = Btt

def __repr__( self ):
s = "My other attribute is " + self.Btt
return s

def SetEqual(self):
Att = self.Btt


I realize the
SetEqual
method above will not work. But how might I go about creating a method in
class B
that will access
class A
and change the value of
self.Att
to be equal to
self.Btt
?

Answer

The following method from B takes a A object and changes its value:

def setEqual(self, a):
    a.Att = self.Btt

Two remarks here.

First, Python does not know about encapsulation, so this is absolutely legal (and Pythonic) to write a.Att from the outside of the A class.

Second, be careful with the assignment, because it only makes a shallow copy. This is not a problem when manipulating immutable objects, but you might want to take a look at the copy module for deep copies.

Comments