Skip to content

Q&A · Answered

How to create a class in Python

asked 9 months, 1 week ago 2259 views 1 answer
13

What is the proper way to define a class with methods and properties?

1 Answer

One accepted
8

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
class User:
    # Class variable
    user_count = 0
    
    def __init__(self, name, email):
        self.name = name
        self.email = email
        User.user_count += 1
    
    def __str__(self):
        return f"User: {self.name}"
    
    @property
    def display_name(self):
        return self.name.title()
    
    @classmethod
    def get_count(cls):
        return cls.user_count
    
    @staticmethod
    def validate_email(email):
        return '@' in email

# Usage
user = User("john", "john@example.com")
print(user.display_name)

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.