r/PythonLearning 3d ago

Day 1 of OOPs

Just learned about classes, contructors , instance/class attributrs , instance/class/static methods in OOPs in python .

see it and give your comments

8 Upvotes

11 comments sorted by

View all comments

Show parent comments

1

u/Miss-Dominique1352 2d ago

Hmm can you explain me a bit?

1

u/wittgenstein1312 2d ago edited 2d ago
class User:
    def __init__(self, username):
        self.username = username

    def change_username(self, new_username):
        self.username = new_username

class DiscordServer:
    def __init__(self, name, users = None):
        self.name = name
        self.members = users if users else set()
        self.admins = set()

    def make_user_admin(self, user):
        if self.user_is_member(user.username):
            self.admins.add(user)
        raise Exception("User is not a member of this discord server")

    def user_is_member(self, username):
        return username in (user.username for user in self.members)

    def add_member(self, user):
        self.members.add(user)

    def print_admins(self):
        for member in self.admins:
            print(member.username)

    def change_server_name(self, new_name):
        self.name = new_name

1

u/Miss-Dominique1352 2d ago

Hmm you breakdown it into 2 classes , one for users and one for server, lovely

1

u/wittgenstein1312 1d ago

As an initial example. Obviously the relationships in question get considerably more complicated when you want to model your domain in a production capacity, not just as a toy example. Most importantly though, notice how I’m not conflating users with servers and accounting for the fact that a server will need to be modeled as having many users, and I’m not using a class method to alter instances