Home > OS >  generic Class in Python
generic Class in Python

Time:12-21

I want to do a generic class in Python with one method

  • This class does not generate its instances
  • Some attributes are set in the body of the class
  • Method of this class uses the set attributes and in the generated classes the output of this method depends on these attributes
  • Method has only one input

I know that without metaclasses will not do, but I do not know how to apply them :)

something like this:

class GenericClass:
  attr_a = ''
  attr_b = ''
  def count(text):
    return len(text)/attr_a   attr_b

class A(GenericClass):
  attr_a = 2
  attr_b = 1

text = "Hello, I'm under the water"
print(A.count(text))
# 14

CodePudding user response:

Defining count as a class method would make that work:

@classmethod
def count(cls, text):
    return len(text) / cls.attr_a   cls.attr_b

CodePudding user response:

class GenericClass:
    def _count(text, a, b):
        return len(text)/a   b

class A(GenericClass):
    attr_a = 2
    attr_b = 1

    def count(text):
        return GenericClass._count(text, A.attr_a, A.attr_b)
    
text = "Hello, I'm under the water"
print(A.count(text))

CodePudding user response:

You could use @staticmethod annotation. Like this:

class GenericClass:

  attr_a = ''
  attr_b = ''

  @staticmethod
  def count(text):
    return len(text)/GenericClass.attr_a   GenericClass.attr_b

class A(GenericClass):
  GenericClass.attr_a = 2
  GenericClass.attr_b = 1


text = "Hello, I'm under the water"
print(A.count(text)) #14

You could also use @classmethod annotation if you want to know the specific class.Check out this question: Creating a static class with no instances

  • Related