What is the pythonic way to overload class variables(properties)?

What is the pythonic way to overload class variables(properties)?

python class attributes
python class variables
python get class attributes
python class inheritance
python update class attributes
python class method overloading
python add attribute to class
python object attributes

Hello!

I need each child class to has own set of constants. I've found a "proper" way with properties and overloading setter methods, but:

  1. I need to define constructor in child classes (which I don't need) and assign values in constructor;
  2. Every instance of class will have copy of this constants in memory (senseless resource consumption);
  3. It looks weird when you define setter, getter and property at all just to use it as constant.

I've done something like this:

class BaseClass:
    def get_a(self):
        raise NotImplementedError("Oooops")

    def get_b(self):
        raise NotImplementedError("Oooops")

class FirstClass(BaseClass):
    def get_a(self):
        return "a"

    def get_b(self):
        return "b"

class SecondClass(BaseClass)
    def get_a(self):
        return "A"

    def get_b(self):
        return "B"

class SomeClass:
    def some_method(self, class_param):
        return "{}-{}".format(class_param.get_a, class_param.get_b)

This method also doesn't solve problems of method with properties (except last), just more compact. There's other way, which I find not good:

class BaseClass:
    pass

class FirstClass(BaseClass):
    A_CONST = "a"
    B_CONST = "b"

class SecondClass(BaseClass)
    A_CONST = "A"
    B_CONST = "B"

class SomeClass:
    def some_method(self, class_param):
        return "{}-{}".format(class_param.A_CONST, class_param.B_CONST)

In fact, it solve all problems and pretty compact, BUT it violates rule of inheritance (isn't it?).

Question: What is the proper way to do this?

P.S. Provided code is simplified example, base class contains methods which I use in child class, please don't write me that base class is useless here.


If you want your base class to indicate that it needs to be subclassed with certain attributes, you can make it an abstract base class.

from abc import ABC, abstractmethod

class Base(ABC):
    @property
    @abstractmethod
    def a(self):
        raise NotImplementedError
    @property
    @abstractmethod
    def b(self):
        raise NotImplementedError

You will then not be allowed to instantiate Base or its subclasses unless they override the abstract methods. You can do either

class First(Base):
    a = 1
    b = 2

to assign class attributes with those names, or

class Second(Base):
    @Base.a.getter
    def a(self):
        return 3
    @Base.b.getter
    def b(self):
        return 4

The benefit of the second approach is that it will raise an error if you try to assign to the property

Second().a = 5  # AttributeError

Overloading Functions and Operators in Python, We only have to define the corresponding special method in our class. To overload a user-defined function in Python, we need to write the function logic in such a way that We have defined the setter and getter methods for these attributes. The Internals of Operations Like len() and []. Every class in Python defines its own behavior for built-in functions and methods. When you pass an instance of some class to a built-in function or use an operator on the instance, it is actually equivalent to calling a special method with relevant arguments.


your second version looks fine to me… each language has their own conventions around what a "class" or "object" means, and this looks reasonably "Pythonic"

one minor comment about the first version, is that Python doesn't care about "overloading", you don't need to include:

class BaseClass:
    def get_a(self):
        raise NotImplementedError("Oooops")

at all, i.e. it's fine to have:

class BaseClass:
    pass

as well in your first version.

another potentially useful tool here is the property decorator, e.g:

class FirstClass(BaseClass):
    @property
    def a(self):
        return "a"

print(FirstClass().a)

would output "a"

Python Class Attributes: Examples of Variables, With this in mind, we can make sense of how Python class attributes handle assignment: If a class attribute is set by accessing the class, it will override the value  Alternatively, you could use a getter and a setter, but using a property is the Pythonic way to deal with it! Let's assume we defined "OurAtt" as a public attribute. Our class has been successfully used by other users for quite a while.


If the key_name : [A_CONST, B_CONST] remains same for child classes, super() will take care of all your concerns (1., 2., 3.).

A 'pythonic' solution would include, to remove duplication's, of any, setter and getter in child classes and let BaseClass() handle these common-tasks.

class BaseClass(object):
    def __init__(self, a, b):
        self._a_const = a
        self._b_const = b
    @property
    def A_CONST(self):
      return self._a_const
    @property
    def B_CONST(self):
      return self._b_const

class FirstClass(BaseClass):
    def __init__(self, _aconst, _bconst):
        # Let Base class object hold my constants but FirstClass Constructor
        # is setting the value. Look SecondClass
        super(FirstClass, self).__init__(_aconst, _bconst)

class SecondClass(BaseClass):
    def __init__(self, _aconst, _bconst):
        # Magic happens here
        super(SecondClass, self).__init__(_aconst, _bconst)

class SomeClass():
    def some_method(self, class_param):
        return "{}-{}".format(class_param.A_CONST, class_param.B_CONST)

firstobj  = FirstClass("a", "b")
secondobj = SecondClass("A", "B")

print(SomeClass().some_method(firstobj))
print(SomeClass().some_method(secondobj))

Class attributes - Object-Oriented Programming in Python, This gives us a way to access the object's properties from inside the object's If our attribute name is stored as a string value in a variable, we have to use the It is also often useful to overload the comparison methods, so that we can use  Python class attributes can lead to elegant code, as well as frustrating bugs. In this guide, we will outline specific use-cases for attributes, properties, variables, objects and more.


9. Classes, data attributes correspond to “instance variables” in Smalltalk, and to “data Data attributes override method attributes with the same name;  In this tutorial, you will learn about Python @property decorator; a pythonic way to use getters and setters in object-oriented programming. Python programming provides us with a built-in @property decorator which makes usage of getter and setters much easier in Object-Oriented Programming.


Python Tutorial: Properties vs. getters and setters, Object oriented programming in Python: instance attributes vs. class attributes and variable and creates "automatically" a getter and a setter for this attributes. design a class in a Javaesque way with getters and setters to encapsulate the Operator Overloading · OOP, Inheritance Example · Slots · Classes and Class  This is how you implement private attributes, getters, and setters in Python. The same process was followed in Java. Let's write the same implementation in a Pythonic way. class PythonicWay: def __init__(self, a): self.a = a You don't need any getters, setters methods to access or change the attributes.


Dive Into Python, Here, the ancestor class has a way to define initial values (by passing a dictionary in the dict (3) Python supports data attributes (called “instance variables" in Java and Java function overloading:Java and Powerbuilder support function  Attributes define a property or feature of a class. They can be variables, It’s usually the first method defined inside a class. This is a more pythonic way to do it. property. Another