Python instance class by name

Dynamic creation of an object instance of a class by name

I have been searching everywhere for this, but have not found a
solution, yet.

What I need is to create an object that is an instance of a class (NOT a
class instance!) of which I only know the name as a string. This what I
tried:

class A:
def __init__(self, id):
self.id = id
def getID(self):
print self.id

ca = new.classobj(‘A’, (), <>)
oa1 = ca()
oa2 = new.instance(ca)

oa1.getID()
Traceback (most recent call last):
File «», line 1, in ?
AttributeError: A instance has no attribute ‘getID’

oa2.getID()
Traceback (most recent call last):
File «», line 1, in ?
AttributeError: A instance has no attribute ‘getID’
Thus, both ways only produce a class instance, but NOT an object of that
class. How can I get a new object instance.
What else needs to be filled in for base_classes and __dict__ in
new.classobj?
Any help is appreciated, this is driving me nuts!

I have been searching everywhere for this, but have not found a
solution, yet.

What I need is to create an object that is an instance of a class (NOT a
class instance!) of which I only know the name as a string. This what I
tried:

class A:
def __init__(self, id):
self.id = id
def getID(self):
print self.id

ca = new.classobj(‘A’, (), <>)
oa1 = ca()
oa2 = new.instance(ca)

oa1.getID()
Traceback (most recent call last):
File «», line 1, in ?
AttributeError: A instance has no attribute ‘getID’

oa2.getID()
Traceback (most recent call last):
File «», line 1, in ?
AttributeError: A instance has no attribute ‘getID’
Thus, both ways only produce a class instance, but NOT an object of that
class. How can I get a new object instance.
What else needs to be filled in for base_classes and __dict__ in
new.classobj?
Any help is appreciated, this is driving me nuts!

Don’t listen to the voices whispering «Use eval()» or «globals() are the way
to go», make it clean and explicit with a dictionary containing all classes
you want to expose:

Out of curiosity — why not to use eval? having a dict like yours makes
things look like your average java factory pattern — some explicit
structure, to which access has to be guaranteed and that requires a
registration.

Of course, if you know that you will always only select the class from a
fixed num of classes, your approach ensures that no non-compliant classes
can be selected — but hey, we’re dynamic here 😉 You never can be totally
sure what you get.

Regards,

I have been searching everywhere for this, but have not found a
solution, yet.

What I need is to create an object that is an instance of a class (NOT a
class instance!)
I’m sorry, I can’t for the life of me figure out what the (semantic)
difference is between «intsance of a class» and «class instance».
of which I only know the name as a string. This what I
tried:

class A:
def __init__(self, id):
self.id = id
def getID(self):
print self.id

ca = new.classobj(‘A’, (), <>)
This creates a new class which will be called «A», displacing your
original class by the same name.
oa1 = ca()
oa2 = new.instance(ca)

oa1.getID()
Traceback (most recent call last):
File «», line 1, in ?
AttributeError: A instance has no attribute ‘getID’

oa2.getID()
Traceback (most recent call last):
File «», line 1, in ?
AttributeError: A instance has no attribute ‘getID’
Thus, both ways only produce a class instance, but NOT an object of that
class.
Yes, they produce an instance of your newly created class.
How can I get a new object instance.
I think you mean to ask «How can I get a new instance of the class
whose name I have in a string?». In other words, you should be asking
yourself, «How can I get my hands on an object whose name[*] I have in a
string?» (One possible approach is shown below.)
What else needs to be filled in for base_classes and __dict__ in
new.classobj?

You can’t do it that way . that way you create a _new_ separate
class called «A».

Here’s how you might achieve what you want:

class A: . def __init__(self, id):
. self.id = id
. def getID(self):
. print self.id
. oa1 = globals()[‘A’](12345)
oa1 oa1.getID() 12345
[*] I’m a bit wary about using «name» here, because I don’t really
mean the name of the class, but the name of a variable that
happens to refer to the class.

For example, consider (in the context established above)
B = A
del A
B.__name__ ‘A’ A.__name__

Traceback (most recent call last):
File «», line 1, in ?
NameError: name ‘A’ is not defined

So, while the name of the class is still «A», it is no longer
known by an identifier of that name.

Don’t listen to the voices whispering «Use eval()» or «globals() are the
way to go», make it clean and explicit with a dictionary containing all
classes you want to expose:

Out of curiosity — why not to use eval? having a dict like yours makes
things look like your average java factory pattern — some explicit
structure, to which access has to be guaranteed and that requires a
registration.

Of course, if you know that you will always only select the class from a
fixed num of classes, your approach ensures that no non-compliant classes
can be selected — but hey, we’re dynamic here 😉 You never can be totally
sure what you get.

It’s probably a matter of taste, but most of the time the use of eval()
suggests more freedom than there actually is. Let’s suppose there are 3
classes A, B, and C that will be used by your eval(), that limitation may
then be enforced in various parts of your code or in the documentation,
while I tend to see exposed = dict(. ) as self-documenting. You can go to
the implementation of one class in the list to look up the interface.

To take an (almost) real-world example from the library, what would you
suppose the following to do?

klass = eval(klass, vars(logging))

What would you do to make the above accept your special-purpose handler
class? I think something like

def registerHandler(name, klass, replace=False):
if not replace and name in availableHandlers:
raise NameClash
availableHandlers[name] = klass

As a side note (not that I think this is important here), eval() is not the
fastest of functions:

$ timeit.py -s»class A: pass» -s»all=dict(A=A)» «all[‘A’]»
10000000 loops, best of 3: 0.147 usec per loop
$ timeit.py -s»class A: pass» «eval(‘A’)»
10000 loops, best of 3: 19.7 usec per loop
Peter

Источник

How to Instantiate a Class in Python

Instantiating a class is a very basic principle of using the Object-Oriented Programming (OOP) approach, and people often confuse this term with something complex. In Python, instantiating a class or creating its instance is done by creating a variable and setting it equal to the class name with parenthesis, just like you would call a function.

This post will act as a guide and explain what is meant by instantiating and the process of instantiating a class in detail.

What Instantiating a Class in Python?

Instantiating a class simply means creating a duplicate/copy of a Python Class, which will contain all the original class’s variables, functions, and attributes. When referring to instantiating from the point of OOP, then it is the process of creating object variables of the class.

Note: Making objects/copies of a class is also called creating instances of a class, thus the term “instantiating” a Class

How to Instantiate a Class in Python?

As mentioned above, to instantiate a class, you need to call the name of the class like you would call a normal function and store the result in a variable. Again, in OOP terms, it is called calling the constructor. However, it causes confusion among people as you do not specify the constructor method with the same name in Python.

Anyhow, the syntax of instantiating a class is as follows:

  • objVar is the variable in which the copy of the class is stored, or it is an object of the class
  • ClassName() is the name of the class to be instantiated into a variable
  • initializeVariableArguments are the arguments that will be used to initialize the values of variables of the class (optional)

Example 1: Instantiate a Basic Class in Python

To demonstrate the method of instantiating a class, you need to first have a class. Therefore, take the following code snippet that will create a class for persons with the names of two people stored in variables and a function to print the name of person1:

class Person:
p1Name = «John Doe»
p2Name = «Rudy Taylor»

def getNameP1 ( self ) :
return self.p1Name;

After that, create a variable named “pObj1” and set it equal to the “Person” class name with round brackets to make a copy of the class inside pObj1:

After that, you can use the pObj1 variable with the dot-operator to access the variables and function of the Person class:

print ( «Directly Access the Variable: » ,pObj1.p2Name )
print ( «Calling the function of Class: » , pObj1.getNameP1 ( ) )

The code snippet for this example is as follows:

class Person:
p1Name = «John Doe»
p2Name = «Rudy Taylor»

def getNameP1 ( self ) :
return self.p1Name;

print ( «Directly Access the Variable: » ,pObj1.p2Name )
print ( «Calling the function of Class: » , pObj1.getNameP1 ( ) )

When you execute this code, it will produce the following result on the terminal:

From this output, you can clearly conclude that you have successfully instantiated the Person class.

Example 2: Instantiating a Class in Python by Passing Values

If a class has un-initialized variables, then you will have to pass them values when creating instances of that class. To demonstrate this, take the following class code:

def __init__ ( self,p1Name,p2Name ) :
self.p1Name = p1Name
self.p2Name = p2Name

def getNameP1 ( self ) :
return self.p1Name;

In this class, the variables p1Name, and p2Name are un-initialized, and you need to pass the value while creating the instance as follows:

After that is done, you can use the pObj1 to access the variables and function just like in the first example:

print ( «Directly Access the Variable: » ,pObj1.p2Name )
print ( «Calling the function of Class: » , pObj1.getNameP1 ( ) )

The complete code snippet for this example is as:

def __init__ ( self,p1Name,p2Name ) :
self.p1Name = p1Name
self.p2Name = p2Name

def getNameP1 ( self ) :
return self.p1Name;

pObj1 = Person ( «Alex» , «Monroe» )

print ( «Directly Access the Variable: » ,pObj1.p2Name )
print ( «Calling the function of Class: » , pObj1.getNameP1 ( ) )

When you execute this program, it will create the following output on the terminal:

You have successfully instantiated a class with un-initialized variables successfully.

Conclusion

Instantiating a Class is the process of creating instances of that class that contain all the variables, functions, and other attributes, which can be called a copy of that class. To instantiate a class, you need to call its constructor method, and in Python, the constructor method is the name of the class followed by round brackets, just like calling a function. Once a class has been instantiated, you can access the attributes of the copied class by using a dot operator.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor’s degree in computer science.

Источник

Читайте также:  Python e226 missing whitespace around arithmetic operator
Оцените статью