TransWikia.com

Python nested classes: self is not defined

Stack Overflow Asked by CMinusMinus on December 13, 2021

I would like to do the following things:

user = Get()

user.username

user.youtube.name
user.youtube.subs

user.twitter.name
user.twitter.subs

user.twitter.open()

This is the code I have:

class Get():
    def __init__(self, username):
        self.username = username

    class youtube:
        self.name = "NameOfTheUserOnYoutube"
        self.subs = 123456

    class twitter:
        def open():
            webbrowser.open("https://www.twitter.com/NameOfTheUserOnTwitter")

        self.name = "NameOfTheUserOnTwitter"
        self.subs = 654321

But when I execute this, the following error occurs:

File "mycode.py", line 9, in youtube
    self.name = "NameOfTheUserOnYoutube"
NameError: name 'self' is not defined

One Answer

A nested class is not automatically an attribute. You need to create attributes as well, and call the class to create instances.

class Get():
    def __init__(self, username):
        self.username = username
        self.youtube = Get.Youtube()
        self.twitter = Get.Twitter()

    class Youtube:
        def __init__(self):
            self.name = "NameOfTheUserOnYoutube"
            self.subs = 123456

    class Twitter:
        def __init__(self):
            self.name = "NameOfTheUserOnTwitter"
            self.subs = 654321
        def open(self):
            webbrowser.open("https://www.twitter.com/" + self.name)

user = Get('barmar')

print(user.username)
print(user.youtube.name, user.youtube.subs)
print(user.twitter.name, user.twitter.subs)

user.twitter.open()

Answered by Barmar on December 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP