0

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
3
  • What do you mean by "This class does not generate its instances"? That it should be impossible to create instances of it? Commented Dec 21, 2022 at 9:45
  • Yes, exactly, but I know how to do it more or less Commented Dec 21, 2022 at 9:59
  • It definitely sounds like you want @classmethod. You will still be able to instantiate classes that use this, but @classmethod will do most of what you want. If you also want to stop people from instantiating the class, you could also raise an error inside the __init__ method. Commented Dec 22, 2022 at 1:28

2 Answers 2

1

Defining count as a class method would make that work:

@classmethod
def count(cls, text):
    return len(text) / cls.attr_a + cls.attr_b
Sign up to request clarification or add additional context in comments.

Comments

0
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))

1 Comment

That requires you to reimplement count on every subclass… Not very generic.

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.