2

Let's say I have a class defined as follow :

class Foo():
   baz = None
   def __init__(self, bar):
       self.bar = bar

Now, in that example Foo.baz is None. Now let's say that this class attribute needs to be an instance of Foo like below:

class Foo():
    baz = Foo("baz")
    def __init__(self, bar):
        self.bar = bar

How would I proceed?

Similarly, is there any way to create a "class property". I know I can assign a lambda function returning a new instance of the class to a class attribute, but I'd rather not have to write the parenthesis.

0

1 Answer 1

2

If you want to use the line baz = Foo("baz") inside a class even before defining Foo earlier; it's not possible ie Python will throw a NameError: name 'Foo' is not defined at you, but here's a workaround to achieve what you intend:

class Foo:
   def __init__(self, bar):
       self.bar = bar
Foo.baz=Foo('foo')

Now Foo.baz is an instance of the Foo class and also baz is a class attribute of the Foo class and hence will be inherited by all instances of the class as well:

myFoo = Foo('myFoo')

You can verify that myFoo.baz.bar is infact 'foo' and not 'myFoo'

print(myFoo.bar) 
# myFoo
print(myFoo.baz.bar)
# foo

Also note that this will cause Foo.baz, Foo.baz.baz, Foo.baz.baz.baz etc. all to be a Foo object because Foo.baz has value Foo('foo') ie an object of Foo class and baz is also a class attribute of Foo.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.