Search code examples
python-3.xclasspropertiessetter

call setter from __init__ in Python


I have a class such as this:

class Ticket:
    def __init__(self, ticket):
        self._subject = ticket.subject
        self._oem = self.oem()
    
    @property
    def oem(self):
        return self._oem

    @oem.setter
    def oem(self):
        #set oem value by extracting it from subject using regex
        self._oem = re.findall('<OEM: (.*?)>', self._subject)[0].strip()

However, on creating an object,

obj = Ticket(test_ticket)

I get an error,

AttributeError: 'Ticket' object has no attribute '_oem'

I've looked at similar questions, but they are not asking the same thing as I am. I want to set the value for oem in the __init__ method, by using the value from a previous variable, not by passing the value from outside.

How do I resolve this issue?


Solution

  • A property setter needs to accept a value, it would be invoked when assigning to the attribute e.g.

    t = Ticket()
    t.oem = value  # this would call call Ticket.oem(t, value)
    

    If this property just uses the data from self._subject then don't write a setter at all. Instead, make the attribute a dynamically calculated and read-only property, like this:

    class Ticket:
        def __init__(self, ticket):
            self._subject = ticket.subject
        
        @property
        def oem(self):
            return re.findall('<OEM: (.*?)>', self._subject)[0].strip()