How to Extract Attributes With Python
An attribute is an object that is part of the value of another object (of which the attribute is also called a "property"). The Python programming language contains object-oriented features such as the ability to create, assign and extract attributes. You can use the attribute mechanism to write Python code in which objects encapsulate structured local states. In particular, a primitive Python operator can extract attribute values from the object that contains them.
Instructions
-
-
1
Define a Python class that contains a class attribute, as in the following sample code:
class MyClass(object):
classAttribute = "All objects in the class have this"
-
2
Extract the value of the class attribute by using the dot operator, as in the following sample code:
myObject = MyClass()
myObject.classAttribute
In this example, the value of the expression in the second line will be, "All objects in the class have this". Object "myObject" will have that attribute, as will all other members of "MyClass".
-
-
3
Assign and extract the value of an instance attribute by using the dot operator, as in the following sample code:
myOtherObject = MyClass()
myOtherObject.instanceAttribute = "Only this object has this"
myOtherObject.instanceAttribute
In this example, the value of the expression in the second line will be, "Only this object has this". Object "myOtherObject" has the instance attribute, but no other instances of "MyClass" (e.g., "myObject") have it.
-
1