Home > Back-end >  Question about setter and calling MyClass()
Question about setter and calling MyClass()

Time:08-26

I have a class like this:

class A:
    b = ""
    @property
    some_property(self):
        raise Error()

    @some_property.setter
    def some_property(self, some_property_var)
        self.b = some_property_var

and i want to do A(some_property='A'), but i can't because

TypeError: A() takes no arguments

. Is there any way to make it work?

CodePudding user response:

I think this is a better example of how to demonstrate what you are trying to do;

#set a property in a class in python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self, name):
        self._name = name
    @property
    def age(self):
        return self._age
    @age.setter
    def age(self, age):
        self._age = age
        
p = Person("John", 36)

So in your case;

class A:
    def __init__(self, b):
        self.b = b
    @property
    def b(self):
        return self._b
    @b.setter
    def b(self, b):
        self._b = b
a = A(1)
print(a.b)

Based on your comments;

#create a class that takes keyword arguments
class A:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
a = A(a=1, b=2)

CodePudding user response:

You can make A.__init__ take variable keyword arguments so that it can iterate through a dict of any given keyword arguments in a generic fashion and call setattr on the object with each argument-value pair to invoke the respective setter:

class A:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)
    
    @property
    def some_property(self):
        raise Exception()

    @some_property.setter
    def some_property(self, some_property_var):
        self.b = some_property_var

print(A(some_property='foo').b)

This outputs:

foo

Demo: https://replit.com/@blhsing/PrimeSadClosedsource

  • Related