shiyon sufa shiyon sufa - 9 months ago 34
Python Question

how to use instance attribute to define a class attribute?

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?

Answer Source

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