Modules
->
OOP
->
Classes and objects
->
Instances as attribute values
Instances as attribute values
Pre code
class Dog: """Represents a dog. attributes: name, age and collar """ class Collar: """Represents a collar. attributes: color and size """
An object attribute can store another object as its value. For example, a dog can have a collar.
We have two classes: Dog
and Collar
.
The Dog
class will include an attribute named collar
,
which will be an instance of the Collar
class.
... strap = Collar() strap.color, strap.size = 'blue', 4 dog = Dog() dog.name, dog.age = "Murki", 2 dog.collar = strap
strap
is an instance of Collar
, which has a color
and size
.
dog
has an attribute collar
and its value is strap
.
... >>> dog.collar <Collar object at 0x00000148DF521010> >>> dog.collar.size 4
The expression dog.collar.size
means, "Go to the object dog
refers to and
select the attribute named collar
; then go to that object and select the attribute named
size
."
We can create a Collar
object and directly assign it to
dog
's collar
attribute:
... >>> dog.collar = Collar() >> dog.collar.size = 5 >>> dog.collar.color = 'black' >>> dog.collar.size 5
Exercises
ⓘ
◄
►
ⓘ
◄
►
ⓘ
◄
►
ⓘ
◄
►
class Person: """Represents a person. attributes: name, best_friend """ p1 = Person() p1.name = "Arta" p2 = Person() p2.name = "Zana" p2.best_friend = p1
Given the above script:
What is type of p2.best_friend: | |
What is value of p2.best_friend.name: |
Exercises
ⓘ
◄
►
ⓘ
◄
►
ⓘ
◄
►
ⓘ
◄
►
class House: """Represents a house. attributes: owner, address """ class Owner: """Represents a house owner. attributes: name """ class Address: """Represents an address. attributes: street """ person = Owner() person.name = "Blerina" addr = Address() addr.street = "Rr. Iliria" h = House() h.owner, h.address = person, addr
Given the above script:
What is type of h.owner: | |
What is value of h.owner.name: |