python class attribute
There are class attributes, and instance attributes.
When you say
class base :
derived_val = 1
You are defining a class attribute. derived_val
becomes a key inbase.__dict__
.
t2=base()
print(base.__dict__)
# {'derived_val': 1, '__module__': '__main__', '__doc__': None}
print(t2.__dict__)
# {}
When you say t2.derived_val
Python tries to find 'derived_val' in t2.__dict__
. Since it is not there, it looks if there is a 'derived_val'
key in any of t2
's base classes.
print(t2.derived_val)
print(t2.__dict__)
# 1
# {}
But when you assign a value to t2.derived_val
, you are now adding an instance attribute to t2
. A derived_val
key is added to t2.__dict__
.
t2.derived_val = t2.derived_val+1
print(t2.derived_val)
print(t2.__dict__)
# 2
# {'derived_val': 2}
Note that at this point, there are two derived_val
attributes, but only
the instance attribute is easily accessible. The class attribute becomes accessible only through referencing base.derived_val
or direct access to the class dict base.__dict__
.
Python class setter - are class attributes reassigned every time a new instance is created?
I realised that I could have easily tested my own question as follows:
import random, string
def get_random_string():
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
random.seed(10)
class TestClassAttributeInstantiation:
class_attr = get_random_string()
def __init__(self):
self.inst_attr = get_random_string()
Then, in an interpreter:
>>> TestClassAttributeInstantiation.class_attr
'OLPFVV'
>>> foo = TestClassAttributeInstantiation()
>>> foo.class_attr
'OLPFVV'
>>> foo.inst_attr
'QENIGY'
>>> bar = TestClassAttributeInstantiation()
>>> bar.class_attr
'OLPFVV'
>>> bar.inst_attr
'ZBWPJH'
As you can see, class_attr
is set when the class is defined rather than when instantiated. This is evident in the fact that all instantiations have a class_attr
with the same value AND in that the reference to the class also has that value.
Class Attributes and Instance Attributes
I am trying to learn the difference between the instance attributes and class attributes and attributes.
there should be two attributes, class attribute
, instance attribute
. or instance attribute
&none-instance attribute
for convenience.
instance attribute
- these are things activated only when
__init__
has been called. - you can only access thenm after Class is initialized, which commonly seen as
self.xxx
. - and methods in class with
self
as its first parameter(normally), these functions are instance methods, and you can only access after you initialized the Class. - and methods in class with
@property
deco, they are instance attributes
common seen instance attribute
class Name(object):
def __init__(self):
self.age = 100
def func(self):
pass
@property
def age(self):
return self.age
class attribute
non-instance attribute
or static attribute
, whatever you call it
- these things stay activated along with Class.
- which means you can access them whenever you need to, like
__init__
, even in__new__
. - they can be called by both
Class
andinstance
.
common seen class attribute
class Name(object):
attr = 'Im class attribute'
there is something else you may should know, class method
, which stay activated along with Class but the difference is class method
can't be called by instance but only Class. example here
class Name(object)
attr = 'Im class attribute'
@classmethod
def get_attr(cls):
return cls.attr
Conclusion
"class attribute" can be called by both instance and Class
"instance attribute" can only called by instance.
How to set class attributes in python
Yes just do
Something.attribute1 = "some value"
Class attributes can be accessed via the class name. You can do this inside any function defined in the class or even outside of it.
Related Topics
Why Aren't Superclass _Init_ Methods Automatically Invoked
N-Grams in Python, Four, Five, Six Grams
How to Get Item's Position in a List
Best Way to Check Function Arguments
How to Equalize the Scales of X-Axis and Y-Axis in Matplotlib
How to Convert Strings in a Pandas Data Frame to a 'Date' Data Type
How to Include Related Model Fields Using Django Rest Framework
Writing to MySQL Database with Pandas Using SQLalchemy, To_Sql
Scipy: Savefig Without Frames, Axes, Only Content
Multithreaded Blas in Python/Numpy
Split List into Smaller Lists (Split in Half)
Plotting a Fast Fourier Transform in Python
Import Error: No Module Named Numpy
Selecting from Multi-Index Pandas
How to Make Two Plots Side-By-Side Using Python