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.

2
  • 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? Commented May 18, 2020 at 1:53
  • Is it **kwarg you are looking for? Commented May 18, 2020 at 2:15

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.