Python Forum
Creating function inside classes using type - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Creating function inside classes using type (/thread-25107.html)



Creating function inside classes using type - wolfmansbrother - Mar-19-2020

I am am stuck, i want to define a class with __init__ hsing the type format

Class A:
  phish = 'Band'
a = A()

# above is the same as

a = type(A,(),{'phish':'Band'}
But, what is the equivalent type() syntax for:

Class A:
   def __init__(self)
      self.phish='Band'
      
a = A()

a = type(A,(),{'__init__':*something here*}
when i print attr.items() i get something like '__init__', <function A.__init__ at 0x0000015D216FB9D8> in the first example

how could i get a similar result in a second example


Complete question: How do i define class functions using type(cls,(),{})?


RE: Creating function inside classes using type - Larz60+ - Mar-19-2020

have you tried to run this?
Class A: will cause a syntax error
class has no title case.
also closing parenthesis on lines 7 (both of them) are missing


RE: Creating function inside classes using type - scidam - Mar-19-2020

You can define unbound method __init__, e.g.

def unbound_init(s):
    s.phish = 'Band'

# and create class instance (and the class) dynamically
a_instance = type('A', (), {'__init__': unbound_init})()

# or maybe you wish one-liner,

a_instance = type('A', (), {'__init__': lambda self: setattr(self, 'phish', 'Band1')})()
Now, a_instance.phish is Band1.


RE: Creating function inside classes using type - wolfmansbrother - Mar-20-2020

(Mar-19-2020, 10:08 PM)Larz60+ Wrote: have you tried to run this?
Class A: will cause a syntax error
class has no title case.
also closing parenthesis on lines 7 (both of them) are missing

No i did not try to run it, thought it sufficed to get my point accross.

(Mar-19-2020, 10:15 PM)scidam Wrote: You can define unbound method __init__, e.g.

def unbound_init(s):
    s.phish = 'Band'

# and create class instance (and the class) dynamically
a_instance = type('A', (), {'__init__': unbound_init})()

# or maybe you wish one-liner,

a_instance = type('A', (), {'__init__': lambda self: setattr(self, 'phish', 'Band1')})()
Now, a_instance.phish is Band1.


Thanks! This is going to be super useful <3