I'd like something like below. Obviously it's invalid syntax, but is it possible to do something like this in python
def make_class(name):
class name:
def __init__(self):
pass
return name
make_class("Test")
a = Test()
I'd like something like below. Obviously it's invalid syntax, but is it possible to do something like this in python
def make_class(name):
class name:
def __init__(self):
pass
return name
make_class("Test")
a = Test()
Defining a local class in your case seems useless. I'd do that if I did want to return it. There some disadvantages when defining local classes:
There are also some advantages of defining a local class:
My suggestion would be to simply define the class globally and, if it should be private, use a name that starts with an underscore, like _MyClass, since this is the convention used to denote private items.
If you want to find a way of creating a new class without using class keyword, Python classes are instances of type classes. You can create a class by doing like this.
Person = type("Person",
(),
{
"sayHello": lambda: "Hello there"})
You have Person class now with sayHello
function defined beforehand.
If you really want to create your function, you can do like this. Actually this is a very bad way. You need to ask your question properly? What do you want to achive?
def create_class(class_name, superclass, namespace):
return type(class_name, superclass, namespace)
Person = create_class("Person",
(),
{
"sayHello": lambda: "Hello there"})
You can do something like this as well.
name = 'Operations'
body = """
def __init__(self, x, y):
self.x = x
self.y = y
def mul(self):
return self.x * self.y
"""
bases = ()
namespace = {}
exec(body, globals(), namespace)
Operations = type(name, bases, namespace)
print(Operations) # output: <class '__main__.Operations'>
instance = Operations(2, 5)
print(instance.mul()) # output: 10
You can define a class and define functions and such in its constuctor, no need to create a new class each time.
Below shows how you can pass in a variable value, a function and how that function can use the object's attributes and how it can be called from another function within the class itself. A lot of stuff, but hopefully by exploring it you will learn a lot!
class my_class:
def __init__(self, name, cool_function):
self.name = name
self.my_function = cool_function
def test(self):
self.my_function(self)
def test_function(self):
print(self.name)
print("Hello World!")
a = my_class("Dave", test_function)
a.test()
# Prints "Dave" and "Hello World!"