DEV Community

Vera-778
Vera-778

Posted on

Attributes can be instance

An attribute of an object can be an instance of another class, or perhaps even the same class.

basil = Person('Basil', 'Fawlty') #basil is an instance here
polly = Person('Polly', 'Sherman', basil) # basil is an attribute of boss of polly here
print(polly.boss.full_name()) #Basil Fawlty

class Person:
    def __init__(self, first_name, last_name, boss = None):
        self.first_name = first_name
        self.last_name = last_name
        self.boss = boss
    def full_name(self):
        return self.first_name + ' ' + self.last_name
    def reverse_name(self):
        return self.last_name + ', ' + self.first_name
Enter fullscreen mode Exit fullscreen mode

Top comments (0)