I want to put Python class methods together in a dictionary.

Asked 2 years ago, Updated 2 years ago, 18 views

 class test:
    def method1(self):
        print('1')

    def method2(self):
        print('2')

the code

 class test:
    methods={}

    def method1(self):
        print('1')
    
    methods['m1'] = self.method1

    def method2(self):
        print('2')

    methods['m2'] = self.method2

as x.methods['m1'] instead of x.method1() for x=test()I would like to specify a key like () so that I can run the method, but I get an error.(NameError: name'self' is not defined)

How should I change it?

python

2022-09-30 12:07

3 Answers

Is it meaningful to do that?I think there are some unexpected restrictions on how to use it, but I can think of setting it in this pattern.
There seems to be still a way to do it, but let me give you an example.

  • _init__Configure with the method
 class test:
    methods={}
    
    def method1(self):
        print('1')
    
    def method2(self):
        print('2')
    
    def__init__(self):
        test.methods ['m1'] = self.method1
        test.methods ['m2'] = self.method2

x = test()
x.methods ['m1']()
x.methods ['m2']()
  • _init__ method, and methods is also an instance variable
 class test:
    
    def method1(self):
        print('1')
    
    def method2(self):
        print('2')
    
    def__init__(self):
        self.methods={}
        self.methods ['m1'] = self.method1
        self.methods ['m2'] = self.method2

x = test()
x.methods ['m1']()
x.methods ['m2']()
  • Do not use self at all
 class test:
    methods={}
    
    def method1():
        print('1')
    
    methods['m1'] = method1
    
    def method2():
        print('2')
    
    methods['m2'] = method2

x = test()
x.methods ['m1']()
x.methods ['m2']()
  • Do not use self. when configuring (=parameter the instance as self when calling)
 class test:
    methods={}
    
    def method1(self):
        print('1')
    
    methods['m1'] = method1
    
    def method2(self):
        print('2')
    
    methods['m2'] = method2

x = test()
x.methods ['m1'] (x)
x.methods ['m2'] (x)


2022-09-30 12:07

The following is how to use properties:

 class test:
  @property
  def methods (self):
    if not hasattr(self, '__methods__'):
      prefix='method'
      self.__methods__={
        m[0]+m[len(prefix):]: getattr(self,m) for mindir(self)
        # Python 3.9 has str.removeprefix method
        # m[0] + m.removeprefix(prefix): getattr(self,m) for mindir(self)
        if not isinstance(getattr(type(self),m),property)
           and m. starts with (prefix)
      }
    return self.__methods__

  def method1(self):
    print('1')
    
  def method2(self):
    print('2')

if__name__=='__main__':
  x = test()
  x.methods ['m1']()
  x.methods ['m2']()

=>
1
2


2022-09-30 12:07

The error occurs because self is not defined in the location where self.method1 is written.

Python's various embedded functions allow you to automatically list the methods defined in the class.

class Test:
    def method_dict(self):
        self_class=type(self)
        name_and_funcs=map(lambda name:(name,getattr(self_class,name))),dir(self_class))
        return dict (filter(lambdanf:callable(nf[1]) and not nf[0].startswith("__"), name_and_funcs))
        
    def method1(self):
        print('1')

    def method2(self):
        print('2')

print(Test().method_dict())
# ==>{'method1':<functionTest.method1 at 0x7f7fd8989310>, 'method2':<functionTest.method2 at 0x7f7fd89893a0>, 'method_dict':<functionTest.method_dict_dict_dict_atx892;gatt892}

It depends on what you want to do, but if you create a key name generation rule, you may be able to do what you want to do.


2022-09-30 12:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.