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
Answer from SayPy on Stack OverflowThe 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
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
python - Calling class attribute without creating an instance to that class - Stack Overflow
Checking my understanding of class attributes vs. instance attributes
python - New instance of class with a non-None class attribute? - Stack Overflow
python - What is the difference between class and instance attributes? - Stack Overflow
What happens if both instance attribute and class attribute are defined?
In that case, the instance namespace takes precedence over the class namespace. If there is an attribute with the same name in both, the instance namespace will be checked first and its value returned.
Python class method versus instance method: What’s the difference?
In Python, a class method is a method that is invoked with the class as the context. This is often called a static method in other programming languages. An instance method, on the other hand, is invoked with an instance as the context.
What is a Python namespace?
A Python namespace is a mapping from names to objects, with the property that there is zero relation between names in different namespaces. Namespaces are usually implemented as Python dictionaries, although this is abstracted away.
There's nothing called t1.var, so of course you can't access it. var is an attribute of a t1 instance; it doesn't exist on the class. Since you can have any number of instances of t1, there's no way for an instance method of t2 to know which t1 instance it should look for the attribute var in without you telling it. You can do this when you instantiate t2.
# t1 class is the same as yours
class t2:
def __init__(self, t1):
self.t1 = t1
def getVar(self):
print self.t1.returnVar(t1)
obj1 = t1()
obj2 = t2(obj1) # give the t2 instance the t1 instance
print obj2.getVar()
If I understand the problem correctly, then you just need to pass your instance of t1 to an instance of t2.
class t2:
def getVar(self, t1):
print t1.returnVar(t1)
t1_instance = t1()
t2_instance = t2()
t2.getVar(t1_instance)
I've got a relatively large dictionary that a class needs to work with, but I only need one copy of the dictionary; I don't need to create a new copy for every instance of the object.
As I understand it, what I can do is this:
class myClass( object ):
theDictionary = { ... }
def __init__(self):
#not relevant, just showing that it's separate from the constructor
And (again, as I understand it) this will result in ONE dictionary that is used by ALL instances-- with the caveat that it is both mutable ( any changes made by one instance will affect all instances ) and not remotely threadsafe.
I was originally thinking of this as memory conservation, but I had an epiphany while I was typing the above. If I've got this correct, one could create a class that is nothing but attributes (and, if needed, thread-safe methods to access said attributes), and make any class that needs to read or modify the data stored in those attributes a child of that class, creating a shared data environment for the entire application without constantly have to pass objects around between classes and/or instances.
I'm really hoping I've got this correct.
As a side note: Is there a way to make a class attribute that's NOT mutable? It's not relevant to the project I'm working on, but I can see situations where I would want a class to operate from a set of data that I didn't want to duplicate for every instance, but didn't want to alter.
EDIT: In case you come across this while googling, this is correct... but incomplete.
There are two ways to access a class variable (in the above case self.theDictionary and myClass.theDictionary). They are interchangeable unless you declare self.theDictionary as an instance variable.
In the case of a dictionary, making a change to it wouldn't be a problem, because when you say (for example) self.theDictionary['word']='meaning', you're not redeclaring self.theDictionary.
But if you wanted to replace the dictionary altogether, you'd want to use myClass.theDictionary = { ... }. The reason for this is that if you say self.theDictionary = { ... }, you're not overwriting the class attribute, you're creating an instance attribute.
Once you create an instance attribute, python will see self.theDictionary as the new dictionary, and you will only be able to access the old one with myClass.theDictionary.
Yes, this is how it is supposed to work.
If a and b belong to the instance of Foo, then the correct way to do this is:
class Foo(object):
def __init__(self):
self.a = []
self.b = 2
The following makes a and b belong to the class itself, so all instances share the same variables:
class Foo(object):
a = []
b = 2
When you mix the two methods -- as you did in your second example -- this doesn't add anything useful, and just causes confusion.
One caveat worth mentioning is that when you do the following in your first example:
foo.b = 5
you are not changing Foo.b, you are adding a brand new attribute to foo that "shadows" Foo.b. When you do this, neither bar.b nor Foo.b change. If you subsequently do del foo.b, that'll delete that attribute and foo.b will once again refer to Foo.b.
Yes, that's exactly what you should expect. When you define a variable on the class, then those attributes are attached to the class, not the instance. You might not always notice that when you assign to an attribute on an instance, the instance picks up the new value, masking the class attribute. Methods that modify in place, like list.append won't give the instance a new attribute, since they just modify existing object, which happens to be an attribute of the class.
Any time every instance of a class should have its own, unique value for an attribute, you should usually set that in the __init__ method, to be sure that it's different for every instance.
only when a class has an attribute that has a sensible default value, and that value is of an immutable type (that cannot be modified in place), such as int or str, should you set attributes on the class.
There is a significant semantic difference (beyond performance considerations):
- when the attribute is defined on the instance (which is what we usually do), there can be multiple objects referred to. Each gets a totally separate version of that attribute.
- when the attribute is defined on the class, there is only one underlying object referred to, so if operations on different instances of that class both attempt to set/(append/extend/insert/etc.) the attribute, then:
- if the attribute is a builtin type (like int, float, boolean, string), operations on one object will overwrite (clobber) the value
- if the attribute is a mutable type (like a list or a dict), we will get unwanted leakage.
For example:
Copy>>> class A: foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[5]
>>> class A:
... def __init__(self): self.foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[]
Here is a very good post, and summary it as below.
Copyclass Bar(object):
## No need for dot syntax
class_var = 1
def __init__(self, i_var):
self.i_var = i_var
## Need dot syntax as we've left scope of class namespace
Bar.class_var
## 1
foo = Bar(2)
## Finds i_var in foo's instance namespace
foo.i_var
## 2
## Doesn't find class_var in instance namespace…
## So look's in class namespace (Bar.__dict__)
foo.class_var
## 1
And in visual form

Class attribute assignment
If a class attribute is set by accessing the class, it will override the value for all instances
Copyfoo = Bar(2) foo.class_var ## 1 Bar.class_var = 2 foo.class_var ## 2If a class variable is set by accessing an instance, it will override the value only for that instance. This essentially overrides the class variable and turns it into an instance variable available, intuitively, only for that instance.
Copyfoo = Bar(2) foo.class_var ## 1 foo.class_var = 2 foo.class_var ## 2 Bar.class_var ## 1
When would you use class attribute?
Storing constants. As class attributes can be accessed as attributes of the class itself, it’s often nice to use them for storing Class-wide, Class-specific constants
Copyclass Circle(object): pi = 3.14159 def __init__(self, radius): self.radius = radius def area(self): return Circle.pi * self.radius * self.radius Circle.pi ## 3.14159 c = Circle(10) c.pi ## 3.14159 c.area() ## 314.159Defining default values. As a trivial example, we might create a bounded list (i.e., a list that can only hold a certain number of elements or fewer) and choose to have a default cap of 10 items
Copyclass MyClass(object): limit = 10 def __init__(self): self.data = [] def item(self, i): return self.data[i] def add(self, e): if len(self.data) >= self.limit: raise Exception("Too many elements") self.data.append(e) MyClass.limit ## 10
In Python, and many other languages, there is a value that means "no value". In Python, that value is None. So you could do something like this:
class User:
username = None
password = None
Those sure sound like instance variables though, and not class variables, so maybe do this:
class User(object):
def __init__(self):
self.username = None
self.password = None
Note how Python assigns the None value implicitly from time to time:
def f():
pass
g = f() # g now has the value of None
First of all, you should rewrite like this:
class User(object):
def __init__(self, username, password):
self.username = username
self.password = password
This way, username and password are instance variables instead of class variables (in your example, they are class variables -- all instance variables need to be defined in __init__ as properties of self). Then, you can initialize a User with whatever username and password you want, including None if you truly want them to have no value.