1

I'm wondering weather it is necessary to define class instance variable within class declarations.

I tried assigning a new instance variable after the object (class instance) was already created, and looks like there is no difference. Are there any caveats in this approach?

class Context():
    def __init__(self, extension):
        self.extension = extension

c = Context('extension+')

print(f"before: {c.__dict__}")

c.new_var = 'new_var_content'
print(c.extension + c.new_var)

print(f"after: {c.__dict__}")

printed:

before: {'extension': 'extension+'}
extension+new_var_content
after: {'extension': 'extension+', 'new_var': 'new_var_content'}
Rob Truxal
  • 5,856
  • 4
  • 22
  • 39
DsL
  • 13
  • 2
  • It’s already been created in `__init__` too, so no, no difference between `extension` and `new_var`. – Ry- Apr 07 '19 at 05:35
  • `c` is nothing but `self,` when you call an instance *method*. So doing `c.attribute` is an explicit way of doing `self.attribute`. Usually, you do every instance manipulation inside a method so that it can be re-used by all class instances. – Nishant Apr 07 '19 at 05:35
  • If I rember correctly in C# or C++ this type of declartion is no allowed. However in Python it looks like OK. – DsL Apr 07 '19 at 06:13

2 Answers2

1

There is no difference between declaring self.foo within a def __init__(self, <arguments>): definition, and declaring it after an object has been instantiated.

Both assignments have instance-level scope.

Given -

class Context:
    i_am_a_class_variable = 'class_string'
    def __init__(self, bar):
        self.bar = bar

See -

  1. class attributes can be accessed without instantiating an object.
>>> Context.i_am_a_class_variable
'class_string'
  1. instance attributes can be assigned during instantiation using the __init__(self) function.
>>> Context.bar
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-8be0704da5be> in <module>                                 
----> 1 Context.bar
>>> instance = Context('bar')
>>> instance.bar
'bar'
  1. instance attributes can be assigned after instantiation, directly
>>> instance = Context('bar')
>>> instance.foo = 'foo'
>>> instance.foo
'foo'
Rob Truxal
  • 5,856
  • 4
  • 22
  • 39
0

Speaking in terms of whether you can assign a value to the property or create a new property, there is no difference if you do it within init or anywhere else after the object is created as in both cases it gets added in dict of the object(unless you use slots)

However, if you want your class to be initialized with desired state (i.e, having some mandatory variables with default/preset values) , you should put it in init. Since init is called implicitly as soon as object is created, you object will be having desired state.

Prashanti
  • 174
  • 7