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?
-
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?juanpa.arrivillaga– juanpa.arrivillaga2017-07-09 20:56:29 +00:00Commented Jul 9, 2017 at 20:56
-
I'm not sure what you mean, could you provide some sample?MSeifert– MSeifert2017-07-09 20:56:42 +00:00Commented Jul 9, 2017 at 20:56
Add a comment
|
2 Answers
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
6 Comments
Moses Koledoye
Why use
__dict__ when you can access the attribute directly: MyClass.attr.SayPy
Yes, you are right, we don't need dict. It just little more handy to deal with missing attributes.
Chris Howe
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.
SayPy
What do you see in: print(class._dict_ ) ?
Chris Howe
'{'dict': <attribute 'dict' of 'armor1' objects>, 'module': 'the_shop', 'weakref': <attribute 'weakref' of 'armor1' objects>, 'doc': None, 'init': <function init at 0x028C1130>}'
|
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
Moses Koledoye
classA = Class_A does not create an instance. I think you want to actually call the class object.Chris Howe
ClassA = Class_A does not work for my code specifically. I have two many classes and the get moved around between two many files