Should I use “self” to define variables / objects of class instanced which I will not need to reach from the outside?

前端 未结 3 707
春和景丽
春和景丽 2021-02-06 10:14

I am not a complete beginner but fairly new to Python. Whilst working on a project today I just had an idea and wondered regarding the usage of \"self

3条回答
  •  爱一瞬间的悲伤
    2021-02-06 10:50

    Looks like you don't need the variable at all then:

    class C:
        def __init__(self, parent=None):
            super(C, self).__init__(parent)
            self.important_property = AnotherClass().bring_the_jewels()
    

    In response to your comment:

    do I need to put self. infront of it if it's gonna be created, referenced and used once during __init__.

    No, you don't. Use a regular variable then, and the object will be garbage-collected after __init__ exits.

    class C:
        def __init__(self, parent = None):
            super(C, self).__init__(parent)
            some_temp_var = AnotherClass()
            self.important_property = some_temp_var.bring_the_jewels()
    

提交回复
热议问题