0

Let's say I have the following class.

class A:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

obj_A = A(y=2) # Dynamically pass the parameters

My question is, how can I dynamically create an object of a certain class by passing only one (perhaps multiple but not all) parameters? Also, I have prior knowledge of the attributes name i.e. 'x' and 'y' and they all have a default value.

Edit: To clear up some confusion. The class can have any number of attributes. Is it possible to create an instance by passing any subset of the parameters during runtime?

I know I can use getters and setters to achieve this, but I'm working on OpenCV python, and these functions are not implemented for some algorithms.

paul-shuvo
  • 1,874
  • 4
  • 33
  • 37
  • 2
    It's a little unclear what you are looking for. In your code, `obj_A` is an instance of class `A`. With `y` as `2` and `x` set to `0`. Isn't that what you want? – Mark May 18 '20 at 01:53
  • Is it **kwarg you are looking for? – Laurent R May 18 '20 at 02:15

2 Answers2

0

Using Approach

Code

import functools

class A:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
      return f'x:{self.x}, y:{self.y}'  # added to see instance data

def partialclass(cls, *args, **kwds):

    class NewCls(cls):
        __init__ = functools.partialmethod(cls.__init__, *args, **kwds)

    return NewCls

Test

# Create Partial Class (setting x only)
A_init = partialclass(A, x=3.14159)

# Setting y dynamically
# Create instance from A_init by setting y
a_2 = A_init(y=2)
print(a_2)  # Out: x:3.14159, y:2

# Create instance from A_init using y default
a_default = A_init()   
print(a_default)       # Out: x:3.14159, y:0
DarrylG
  • 16,732
  • 2
  • 17
  • 23
0

I am guessing you are looking for dynamic class creation. If so, you should use type(name,bases,dict).

check this previous strackoverflow thread

111Seven
  • 71
  • 4