Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I recursively create class properties in Python?

Tags:

python

Python supports creating properties "on the fly", like so.

class MyClass:
    def __init__(self):
        pass

x = MyClass
x.new = 5
print(x.new)  # prints 5

But this is a tad ugly. I have to have some instruction within the class, either a function or a class property definition.

But the main hindrance is this...

x.first.second = 1  # this will raise

And it raises because first doesn't exist, obviously. I would have to do something like this instead.

x.first = MyClass()
x.first.second = 1
print(x.first.second)

I want to recursively create properties as they're needed. Is this possible?

like image 401
DeepDeadpool Avatar asked May 22 '20 19:05

DeepDeadpool


People also ask

How do you create a class property in Python?

The following example shows how to create a Circle class with a handy property to manage its radius: # circle.py class Circle: def __init__(self, radius): self. _radius = radius def _get_radius(self): print("Get radius") return self. _radius def _set_radius(self, value): print("Set radius") self.

Can a class method be recursive?

Method invoked by the built-in len function. Method invoked for element selection: sequence[index] Method invoked to display an object as a string. Yes, this call is recursive There's the base case! Methods can be recursive too!

Do Python classes have properties?

Class Properties In Python, a property in the class can be defined using the property() function. The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#.

What is the use of self keyword in Python?

self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes.


1 Answers

Use __getattr__ to create a new attribute namespace and return. __eq__ is implemented. The behavior is similar to types.SimpleNamespace.

class Namespace:
    def __init__(self):
        pass

    def __getattr__(self, item):
        ret = Namespace()
        setattr(self, item, ret)
        return ret

    def __eq__(self, other):
        return isinstance(other, Namespace) and vars(self) == vars(other)


ns = Namespace()
ns.first.second = 1

print(ns.first.second)  # 1

However, this has side effect

print(ns.unknown)   # <__main__.Namespace object at 0x0000025FC1E5B400>
like image 152
Aaron Avatar answered Oct 18 '22 18:10

Aaron