1

I'm trying to use the name in my init for my class attribute, attr but it seems that's impossible. here's the code:

class B:

    def __init__(self, val):
        self.val = val

    def __get__(self, instance, owner):
        return owner.valEditNew(self.val)

    def __set__(self, instance, value):
        return


class A:

    def __init__(self, name = 'def_name'):
        self.name = name

    attr = B('G120')

    def valEditNew(val):
        val += ' @edited'
        return val

a = A('JJ')
print(a.attr)

that's it if i use self.name or name or ... in place of G120>>> builtins.NameError: name 'self' is not defined if that's not possible, can you show me the way?

1 Answer 1

1

If you want to access attribute of the instance that contains the descriptor object, use instance parameter of __get__ / __set__:

class B:

    def __get__(self, instance, owner):
        return instance.valEditNew(instance.name)  # <---

    def __set__(self, instance, value):
        return


class A:

    attr = B()

    def __init__(self, name='def_name'):
        self.name = name

    def valEditNew(self, val):
        val += ' @edited'
        return val


a = A('JJ')
print(a.attr)
# prints => JJ @edited
Sign up to request clarification or add additional context in comments.

3 Comments

I know that I'm overriding get and set methods here... where can I find the original ones ?
@shiyonsufa, B is not subclass of any class, but object which does not have __get__, __set__; no overriding is done. Try object.__get__ in interactive shell.

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.