2

I was wondering if it is possible to use an attribute of a class from another file without creating an object from that class, for example, if I have Class_A in File_A and I import Class_A into File_B do I have to use Class_A as an object in File_B in order to access its attributes?

2
  • The whole point of classes is to serve as a template for the creation of objects. Sounds like a fundamental design problem if you want an instance attribute without an instance. Why is this an attribute to begin with, an not a module level variable? Commented Jul 9, 2017 at 20:56
  • I'm not sure what you mean, could you provide some sample? Commented Jul 9, 2017 at 20:56

2 Answers 2

6

The simplest way:

In [12]: class MyClass(object):
...:         attr = 'attr value'

In [15]: MyClass.attr
Out[15]: 'attr value'

You can use __dict__ attribute also:

__dict__ is the dictionary containing the class's namespace.

In [15]: MyClass.__dict__.get('attr', None)
Out[15]: 'attr value'

Use staticmethod decorator if you need to use a method:

In [12]: class MyClass(object):
...:         @staticmethod
...:         def the_static_method(x):
...:             print(x)


In [15]: MyClass.the_static_method(2)
Out[15]: 2
Sign up to request clarification or add additional context in comments.

6 Comments

Why use __dict__ when you can access the attribute directly: MyClass.attr.
Yes, you are right, we don't need dict. It just little more handy to deal with missing attributes.
the problem is whenever I use class.name it says the class has no attribute name even though it does, I've checked the spelling.
What do you see in: print(class._dict_ ) ?
'{'dict': <attribute 'dict' of 'armor1' objects>, 'module': 'the_shop', 'weakref': <attribute 'weakref' of 'armor1' objects>, 'doc': None, 'init': <function init at 0x028C1130>}'
|
0

There really is no reason to create a new object in other to utilize the properties and methods of another object.

You only want to create an instance of Class_A in File_B to use it's properties and methods.

For example:

import Class_A

#instance of Class_A
classA = Class_A('params')

#property1 is a property in classA
classA.property1

#doSomething is a method in classA
classA.doSomething()

Read more about OOP here http://www.python-course.eu/object_oriented_programming.php

2 Comments

classA = Class_A does not create an instance. I think you want to actually call the class object.
ClassA = Class_A does not work for my code specifically. I have two many classes and the get moved around between two many files

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.