A simple way to do it is with SimpleNamespace
:
from types import SimpleNamespace
class Something:
@staticmethod
def _did_something(input):
print(input)
subspace = SimpleNamespace(
my_var="stuff",
do_something=_did_something
)
In simple use:
>>> f = Something()
>>> f.subspace.my_var
stuff
>>> f.subspace.do_something("hello")
hello
In this case, items which do not require reference to internal class variables can be used with a @staticmethod
definition, and will operate without instantiation as well:
>>> Something.subspace.my_var
stuff
>>> Something.subspace.do_something("goodbye")
goodbye
For more complex operations, where a reference to another value is needed, the class requires instantiation such that the internal parameters can be set:
from types import SimpleNamespace
class Something:
def __init__(self):
# must be assigned after class instantiation
self.other_subspace.tell_secrets = self._other_func
@staticmethod
def _did_something(input):
print(input)
subspace = SimpleNamespace(
my_var="stuff",
do_something=_did_something
)
def _other_func(self,input):
print(self.other_subspace.secret + " and " + input)
other_subspace = SimpleNamespace(
secret="mayonaise",
sauce="duck",
tell_secrets=None #placeholder, set after instantiation
)
In use, the values can then be referenced after object creation:
>>> f = Something()
>>> f.other_subspace.sauce
duck
>>> f.other_subspace.tell_secrets("ketchup")
mayonaise and ketchup
do_smth
need access to the instance, like regular methods? – Bindweedself.subspace = self.another_subspace = self
in the__init__
method. Of course, that's not creating separate namespaces, although it does allow the calling syntax you describe. OTOH, it doesn't stop people from doingsmth.do_smth()
. – BrandtSomething.__init__(... self.subclass = Subclass(owner=self), self.another_subclass = AnotherSubclass(owner=self...
, kinda achieve this? where the subclasses could lookup whatever info they need from their owner and your namespace would fit your intent. Subclass would have ado_smth
method. – Kraft