Home > Net >  Class attributes/methods without defining them Python?
Class attributes/methods without defining them Python?

Time:08-28

I am seeing the code shown below for the 1st time, which I have never learned or seen anywhere else before. I have only seen Class attributes or Instance attributes. How does this one below work? Can we just add any class attributes/methods like this way?

class Globals:
    pass

g = Globals()

g.tasks = []
g.diff_list = []
g.pdf_list = []
g.tstamp = None
g.terminated = False
g.num_task_retries = 4

Thank you.

CodePudding user response:

Unless you specify otherwise using __slots__, Python classes are basically just wrappers over dictionaries. They can be given arbitrary attributes at any time. To prevent this, you specify __slots__ on the class, which limits the attributes that can be added, and has performance benefits as well:

class Globals:
    __slots__ = ["a"]

g = Globals()
g.a = 1  # Fine
g.b = 2  # AttributeError: 'Globals' object has no attribute 'b'
  • Related