Home > Enterprise >  Python access a class attribute without initializing?
Python access a class attribute without initializing?

Time:12-18

I have two files where each one contains a class:

# file1.py
class Class1:
    def __init__(self):
        self.d = dict()

    @property
    def get(self):
        return self.d
    

obj1 = Class1()
obj1.d["a"] = 1
obj1.d["b"] = 2

# file2.py
from file1 import Class1 

class Class2:   
    def print_val(self):
        for i in Class1().get:
            print(i)

I am trying to access the attribute d from Class1 in Class2 without initializing Class1. The following currently returns an empty dict which makes sense.

Class2().print_val()
{}

CodePudding user response:

The class Class1 does not have an attribute d. Only objects of type Class1 have an attribute d. If you want to print the members of obj1.d, you can certainly do that, but you'll have to pass obj1 to print_val somehow.

CodePudding user response:

You could create a class variable on Class1, as you don't want to instantiate Class1.

class Class1:
    d = dict()


Class1.d['a'] = 'A'
Class1.d['b'] = 'B'


class Class2:
    def print_val(self):
        print(Class1.d)


c2 = Class2()
c2.print_val()

Out:

{'a': 'A', 'b': 'B'}
  • Related