This question already has answers here:
Can't set attributes on instance of "object" class
(7 answers)
Closed 5 years ago.
I recently noticed in Python that if I create a dict subclass I can add attributes, however this isn't the case with instances of dict. I.E:
class aDict(dict):
pass
myDict = aDict({"name" : "A"})
myDict.color = "red"
print(myDict.color) #"red"
myOtherDict = dict({"name" : "B"})
myOtherDict.color = "green" #"AttributeError: 'dict' object has no attribute color"
You are interacting with myDict's
__dict__ which is the attribute dictionary given to an object, this is different to the myOtherDict which is the inbuilt dictionary. You can see the difference with how you interact with these by trying:
dir(myDict)
dir(myOtherDict)
and you can see what is accessible via myDict's dict attribute (and compare it with the lack of attribute on myOtherDict via vars()
vars(myDict)
vars(myOtherDict)
There's some more information available here and here that helped me to understand your problem.
Related
This question already has answers here:
In a Python object, how can I see a list of properties that have been defined with the #property decorator?
(5 answers)
Closed 2 years ago.
In Python, how can I get all properties of a class, i.e. all members created by the #property decorator?
There are at least two questions[1, 2] on stackoverflow which confound the terms property and attribute, falsely taking property as a synonym for attribute, which is misleading in Python context. So, even though the other questions' titles might suggest it, they do not answer my question.
[1]: Print all properties of a Python Class
[2]: Is there a built-in function to print all the current properties and values of an object?
We can get all attributes of a class cls by using cls.__dict__. Since property is a certain class itself, we can check which attributes of cls are an instance of property:
from typing import List
def properties(cls: type) -> List[str]:
return [
key
for key, value in cls.__dict__.items()
if isinstance(value, property)
]
This question already has answers here:
Instance is an "object", but class is not a subclass of "object": how is this possible?
(3 answers)
isinstance() and issubclass() return conflicting results
(4 answers)
Closed 5 years ago.
In Python 2, why are instances of old style classes still instances of object even when they do not explicitly inherit from object?
class OldClass:
pass
>>> isinstance(OldClass(), object)
True
Before testing this, I would have concluded that isinstance(x, object) == True would imply that x is an instance of a subclass of object and thus an instance of a new style class, but it appears that all objects in Python 2 are instances of object (yes, I know how obvious that sounds).
Digging around further, I found some other seemingly odd behavior:
>>> issubclass(OldClass, object)
False
I was under the impression that isinstance(x, SomeClass) is virtually equivalent to issubclass(x.__class__, SomeClass), but apparently I'm missing something.
This question already has answers here:
Why can't you add attributes to object in python? [duplicate]
(2 answers)
Can't set attributes on instance of "object" class
(7 answers)
Closed 9 years ago.
I just realized that:
class A(object): pass
a = A()
a.x = 'whatever'
Works (does not raise an error and creates a new x member).
But this:
a = object()
a.x = 'whatever'
Raises:
AttributeError: 'object' object has no attribute 'x'
While I probably would never use this in real production code, I'm a bit curious about what the reason is for the different behaviors.
Any hints ?
Probably because of __slots__. By default your class have dict of all atributes which can be added to like in your first example. But that behaviour can bi overriden by using slots.
Also, some classes like datetime which are implemented in C also can not be extended with new attributes at runtime.
Workaround for such classes is to do something like :
class MyObject(): # extend that class, here we extend object
pass # add nothing to the class
o = MyObject()
o.x = 'whatever' # works
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
python class inherits object
In Python 2.7, what is the difference between:
class MyClass(Object):
and
class MyClass:
What does the Object do?
The Object in this case the base class of MyClass, meaning that it 'inherits' the methods and variables of Object unless overwritten. Inheriting from object, however, creates a 'new-style class' as opposed to an 'old-style class'. For more information, see jozzas' comment
See this tutorial for information about inheritance.
This question already has answers here:
List attributes of an object [duplicate]
(18 answers)
Closed 4 years ago.
For example I have next python class
class Myclass():
a = int
b = int
Imagine that I don't know the name this class, so I need to get the names of attributes? ("a" and "b")
If you want all (including private) attributes, just
dir(Myclass)
Attributes starting with _ are private/internal, though. For example, even your simple Myclass will have a __module__ and an empty __doc__ attribute. To filter these out, use
filter(lambda aname: not aname.startswith('_'), dir(Myclass))