0

Can someone help me? I have something like:

class MyClass:
    def __init__(self, *, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

    @test_dec('some param', self.arg2)
    def test_func():


        pass

But it doesn't work. So, how can I put self.arg2 to test_dec?

I want to do something like:

import socketio
sio = socketio.AsyncServer()

class MyClass: 
    def __init__(self, options): 
        self.options = options 

    @sio.on('connect', namespace=self.options['namespace']) 
    def func(): pass
  • 2
    That makes no sense. There is no `self` in that context. What if I never create an instance of `MyClass`? What is `self` then? What is your decorator supposed to do, and why does it need access to the instance? – Aran-Fey Sep 06 '18 at 10:46
  • Related: [Access self from decorator](//stackoverflow.com/q/7590682) – Aran-Fey Sep 06 '18 at 10:47

2 Answers2

0

At first when there is nothing, there is no self. if you want to do it you should do something like this:

class MyClass:
    arg = 'something'       

    def __init__(self, *, arg1, arg2):
        self.arg1 = arg1
        self.arg = arg2

    @test_dec('some param', arg)
    def test_func():
        pass

But the value after initiating the class dosent effect the decorator. you should decorate you class with that arg.


or as Aran-Fey said check this link out, it will help you to decorate yourr class.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

You can access arg2 in the decorator via the reference to self:

def test_dec(param):
  def outer(f):
    def wrapper(_self):
      _val = _self.arg2
      #do something
    return wrapper
  return outer

class MyClass:
  def __init__(self, *, arg1, arg2):
    self.arg1 = arg1
    self.arg2 = arg2
  @test_dec('some param')
  def test_func(self):
    pass
Ajax1234
  • 69,937
  • 8
  • 61
  • 102