Python Reflected and Called Objects

I have a two-part question.

>>> class One(object):
...     pass
... 
>>> class Two(object):
...     pass
... 
>>> def digest(constr):
...     c = apply(constr)
...     print c.__class__.__name__
...     print constr.__class__.__name__
... 
>>> digest(Two)
Two
type

How to create an object "Two"? Neither constr () nor c () work; and it seems that the application turns it into a type.

What happens when you pass a class and instance to a method?

+3
source share
4 answers

How to create an object "Two"? Neither constr () nor c () work; and it seems that the application turns it into a type.

The above comment was made regarding this code:

>>> def digest(constr):
...     c = apply(constr)
...     print c.__class__.__name__
...     print constr.__class__.__name__

apply(deprecated: see @pyfunc answer), of course, does not turn a class Twointo a type: it is already one.

>>> class Two(object): pass
... 
>>> type(Two)
<type 'type'>

- : type. , .

>>> two = Two()
>>> type(two)
<class '__main__.Two'>

, , type. .

>>> Three = type('Three', (Two, ), {'foo': 'bar'})
>>> type(Three)
<type 'type'>
>>> three = Three()
>>> type(three)
<class '__main__.Three'>

, type - , . : , , . type aka.

,

, ?

. - type, . , , , , , : .

+1

- , :

def createMyClass ( myClass ):
    obj = myClass()
    return obj

class A ( object ):
    pass

>>> x = createMyClass( A )
>>> type( x )
<class '__main__.A'>
+5

:

def InstanceFactory(classname):
   cls = globals()[classname]
   return cls() 

class A(object):
   def start(self):
       print "a.start"

class B(object):
   def start(self):
        print "b.start"

InstanceFactory("A").start()
InstanceFactory("B").start()

:

def InstanceFactory(modulename, classname):
    if '.' in modulename:
        raise ValueError, "can't handle dotted modules yet"
    mod = __import__(modulename)
    cls = getattr(mod, classname]
    return cls() 
+1

. () 2.3

.

apply(f, args, kwds)  -->  f(*args, **kwds)

/ :

  • ()
  • ()
  • intern()

: Classname() .

0

Source: https://habr.com/ru/post/1773192/


All Articles