[python] class attribute vs instance attribute

Seungrok Yoon (Lethe)·2024년 3월 15일
0

잊지 않으려고 저장하는 ChatGPT와의 대화

Defining a signal in the __init__ function of a class versus defining it outside the __init__ function has a significant difference in terms of scope and visibility.

  1. Defining in __init__:
    • When you define a signal in the __init__ function of a class, it becomes an instance attribute of that class. This means that each instance of the class will have its own signal attribute.
    • Signals defined in __init__ are accessible only within the instance of the class where they are defined. Other instances of the same class will have their own separate signal attributes.

Example:

from PySide6.QtCore import QObject, Signal

class MyClass(QObject):
    def __init__(self):
        super().__init__()
        self.my_signal = Signal()

# Usage
obj1 = MyClass()
obj2 = MyClass()

# obj1 and obj2 have their own separate instances of my_signal
  1. Defining outside __init__:
    • When you define a signal outside the __init__ function (as a class attribute), it becomes a class-level attribute.
    • Signals defined outside __init__ are shared among all instances of the class. They behave like static members of the class.

Example:

from PySide6.QtCore import QObject, Signal

class MyClass(QObject):
    my_signal = Signal()

# Usage
obj1 = MyClass()
obj2 = MyClass()

# obj1 and obj2 share the same instance of my_signal

In Summary:

  • If you define a signal in the __init__ function, each instance of the class will have its own signal attribute. This can be useful if you need different instances to emit signals independently.
  • If you define a signal outside the __init__ function, it becomes a class-level attribute shared among all instances. This can be useful if you want all instances to share the same signal, such as for notifying about global events or state changes.
profile
안녕하세요 개발자 윤승록입니다. 내 성장을 가시적으로 기록하기 위해 블로그를 운영중입니다.

0개의 댓글