Attributes
Related code
class Dog: """Represents a dog.""" dog = Dog()
We can assign values to an instance using dot notation:
... dog.name = "Murki" dog.age = 2
We assigned values to named elements of an object. These elements are called attributes.
Now dog has two attributes, name and age.
The variable dog refers to a Dog object, which contains two attributes. name attribute refers to a string, age refers to an integer. You can read the value of an attribute using the same syntax:
... >>> dog.name Murki >>> age = dog.age >>> age 2
The expression dog.age means, "Go to the object dog refers to and get the value of age." In the example, we assign that value to a variable named age. There is no conflict between the variableage and the attribute age.
Exercises
Assign three attributes to it, model, price and year, with values a string, a float and an integer respectively.
Create a class and any instance of it, save it to a variable, and assign any attribute to this instance.
class Movie: """Represents a movie.""" movie = Movie() movie.title, movie.year = "The Shawshank Redemption", 1994
Given the above script
What is name of the defined class: | |
What variable is the only class instance assigned to: | |
How many attributes does the only class instance have: | |
What is the first defined attribute name: | |
What is the second defined attribute name: | |
What is value of title movie attribute: | |
What is value of year movie attribute: |
Exercises
Create a class named Book
Create an instance of Book and assign it to book
Assign two attributes to book, title and pages, with values "Of Mice And Men" and 120 respectively.
Create a class named Computer
Create an instance of Computer and assign it to pc
Assign two attributes to pc, brand and ram, with values "Lenovo" and 16 respectively.
Create a class that represents city
Create an instance of it and assign it to c
Assign three attributes to it, name, population and is_capital, with values a string, an integer and a boolean respectively.
Create a class, any instance of it, save them to variables, and assign any attribute to this instance.
class Bike: """Represents a bike.""" bk = Bike() bk.brand = "Trek"
Given the above script
What is name of the defined class: | |
What variable is the only class instance assigned to: | |
How many attributes does the only class instance have: | |
What is the only defined attribute name: | |
What is value of the only defined attribute: |