1

Please make some code that recomputes object._x whenever object.x is updated. I intend object._x to be a "private" attribute of object and object.x to be a "dummy variable" whose only purpose is to set the value of object._x.

class tihst(object):
    def __init__(self,object):
        self.x=object
        self.xRecall()
    def xPrivate(self):
        if type(self.x)==float:
            self._x=self.x
        elif type(self.x)==int:
            self._x=float(self.x)
        elif type(self.x)==str:
            self._x=self.x
        else:
            self._x="errorStatus001"
    def xRecall(self):
        print "private x is :"
        self.xPrivate()
        print self._x

aone=tihst("002")
print vars(aone)

For example.: If a user makes a statement such as object.x="5.3" then the instruction object.xPrivate() should too occur.

EricVonB
  • 238
  • 3
  • 11

2 Answers2

2

It sounds to me like you want x to be a property. A property is an object you store in a class that calls "getter" and "setter" functions when it is accessed or assigned to as an attribute on an instance of the class.

Try this:

class MyClass(object):
    def __init__(self, val):
        self.x = val   # note, this will access the property too

    @property          # use property as a decorator of the getter method
    def x(self):
        return self._x

    @x.setter          # use the "setter" attribute of the property as a decorator
    def x(self, value):
        if isinstance(value, (float, int, str)):  # accept only these types
            self._x = val
        else:
            self._x = "Error" # it might be more "Pythonic" to raise an exception here
Ben
  • 6,687
  • 2
  • 33
  • 46
Blckknght
  • 100,903
  • 11
  • 120
  • 169
0

You can also use property like this:

class MyClass(object):

    def __init__(self, x):
        self._x = x

    def access_x(self):
        print 'Accessing private attribute x:', self._x
        return self._x

    def change_x(self, new_x):
        print 'Changing private attribute x to', new_x
        # You can add some extra logic here ...
        self._x = new_x

    x = property(access_x, change_x)

You can see the property in action by creating an instance of the class:

>>> obj = MyClass('123')

>>> obj.x
Accessing private attribute x: 123
'123'

>>> obj.x = 456
Changing private attribute x to 456
juliomalegria
  • 24,229
  • 14
  • 73
  • 89