1

I want to create property method dynamically.

It means, for example, i want first class A to be equivalent with second one.

Is there any way?

class A(object):
  def __init__(self):
    self._a = 10
    self.createPropertyMethod(a, self._a, getFunc, setFunc, delFunc)

  def createPropertyMethod(self, name, value, getFunc, setFunc, delFunc)
     #TODO

.

class A(object):
  def __init__(self):
    self._a = 10

  @property
  def a(self):
    return getFunc(self._a)
  @a.setter
  def a(self, value):
    setFunc(self._a, value)
  @a.deleter
  def a(self):
    delFunc(self._a)

1 Answer 1

3

You can't, not on instances. The property object needs to be part of the class for the descriptor protocol on which it relies to work.

You can use the __getattr__, __setattr__ and __delattr__ hooks instead to proxy attribute access dynamically.

Sign up to request clarification or add additional context in comments.

4 Comments

Does creating a decorator on class would work what @asleea wants to achieve ? Well i am not very much comfortable in the new style classes thing.
@kingsdeb: a class decorator would alter the class, not the instance. So, yes, you can create property objects in the decorator, add those to the class and have them work.
@Martin Pieters -Would you show me such a code with little more explanation please?
@kingsdeb: no, because that's outside scope of this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.