1e. Class methods and members Flashcards
What are class methods and properties?
They are methods and properties that are shared across all instances of a class.
What convention is used for naming class attributes?
SCREAMING_SNAKE_CASE
How do you define a class method?
By using the @classmethod decorator. The rest is identical to how you define an instance method.
eg. @classmethod def do_something(cls): pass
What’s the first parameter that a class method takes?
The class itself. Like self
for instance methods, we don’t need to pass this parameter in manually.
What are static methods?
They are methods that don’t modify the state of either the class or specific objects.
How do you define a static method?
By using the @staticmethod decorator. The rest is identical to how you define an instance method.
eg. @staticmethod def do_something(): pass
What scenario is a static method most useful for?
They are useful when a method doesn’t need to access any properties of an object or a class but still makes sense for it to be a part of a class. In other words, namespacing.
How do you define a class attribute?
By defining an attribute outside the \_\_init\_\_
function without using self.