pythonbeginner

Classmethod Staticmethod

Advanced Python pattern: classmethod-staticmethod

python
class User:
    domain = 'example.com'

    def __init__(self, email: str):
        self.email = email

    @classmethod
    def from_username(cls, username: str) -> 'User':
        return cls(f'{username}@{cls.domain}')

    @staticmethod
    def is_valid(email: str) -> bool:
        return '@' in email and '.' in email.split('@')[-1]

u = User.from_username('alice')
print(u.email, User.is_valid(u.email))

Use Cases

  • advanced programming
  • patterns

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.