13
What is the proper way to define a class with methods and properties?
Loading...
Q&A · Answered
What is the proper way to define a class with methods and properties?
Accepted answer
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)Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.