12.3. OOP Attribute About
Attributes are also known as "Properties" or "Fields"
Attributes store information for instances
Access field values using dot (
Variable inside the class. In Python, methods also can be described as attributes, but justification for that is a bit more complex which will be introduced later in a book.
Variable inside the class. Should not change during lifetime of an object.
Variable inside the class. Changes during lifetime of an object. Represents current state of an object.
Container for storing related data
Class example with distinction of properties and state attributes.
An example "Glass with Water" can illustrate the distinction of properties and state attributes:
net mass (without water)
volume (how much water is currently in the glass)
gross mass = net mass + water mass (water mass depends on its volume used))
12.3.2. What are attributes?
Identifiers and scalars creates values:
>>> point_x: int >>> point_y: int >>> point_z: int
Values with relations creates structure:
>>> point: tuple[int,int,int]
Data with meaning creates data:
>>> point: dict[str,int]
Information with context and relations creates information:
>>> class Point: ... x: int ... y: int ... z: int
>>> x = 1 >>> y = 2 >>> z = 3
Class creates space, in which names has meaning:
>>> class Point: ... x: int ... y: int ... z: int >>> >>> >>> point = Point() >>> point.x = 1 >>> point.y = 2 >>> point.z = 3
12.3.4. Use Case - 0x01
>>> class Laptop: ... cpu: float ... ram: int ... ssd: int >>> >>> >>> macbook = Laptop() >>> lenovo = Laptop() >>> hp = Laptop() >>> asus = Laptop()
12.3.5. Use Case - 0x02
>>> class Date: ... year: int ... month: int ... day: int >>> >>> >>> # Gagarin - first man to leave Earth >>> gagarin = Date() >>> gagarin.year = 1961 >>> gagarin.month = 4 >>> gagarin.day = 12 >>> >>> # Armstrong - first man to walk on the Moon >>> armstrong = Date() >>> armstrong.year = 1969 >>> armstrong.month = 7 >>> armstrong.day = 21
12.3.6. Use Case - 0x03
>>> class Date: ... year: int ... month: int ... day: int >>> >>> >>> class Person: ... firstname: str ... lastname: str ... date_of_birth: Date ... height: float ... weight: float
12.3.7. Good Practices
Attributes should be defined only in
More information in OOP Init Method