What are the other main methods in Python besides magic methods?
sobes.tech AI
Answer from AI
In Python, besides "magic" methods (also called "dunder" - double underscore methods), there are many other core methods that are part of the standard library or built into the language.
Here are some categories and examples:
1. Built-in functions:
These functions are available without import and provide basic functionality.
# Examples of built-in functions
len([1, 2, 3]) # Returns the length of the object
print("Hello, world!") # Prints text to the console
type(10) # Returns the type of the object
isinstance("abc", str) # Checks if the object is an instance of a class or subclass
2. String methods:
These methods work with string objects.
# Examples of string methods
"hello".upper() # Converts string to uppercase
"world".startswith("wo") # Checks if string starts with the specified substring
"добрый день".split() # Splits the string into a list by delimiter
3. List methods:
These methods work with list objects.
# Examples of list methods
my_list = [1, 2, 3]
my_list.append(4) # Adds an element to the end of the list
my_list.sort() # Sorts the list in place
my_list.pop() # Removes and returns the last element of the list
4. Dictionary methods:
These methods work with dictionary objects.
# Examples of dictionary methods
my_dict = {"a": 1, "b": 2}
my_dict.keys() # Returns a view of the dictionary's keys
my_dict.values() # Returns a view of the dictionary's values
my_dict.get("c", 0) # Returns the value for key "c" or default if not found
5. Set methods:
These methods work with set objects.
# Examples of set methods
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.union(set2) # Returns a new set with elements from both sets
set1.intersection(set2) # Returns a new set with common elements
6. File system object methods:
These methods are used for working with files and directories.
# Examples of file methods
# Assuming 'file' is an open file object
# file.read() # Reads the entire file
# file.write("some text") # Writes text to the file
# file.close() # Closes the file
7. Class and instance methods:
These are methods defined within classes that work with instances or the class itself.
# Examples of class and instance methods
class MyClass:
def instance_method(self):
# Instance method
pass
@classmethod
def class_method(cls):
# Class method
pass
@staticmethod
def static_method():
# Static method
pass
# my_instance = MyClass()
# my_instance.instance_method()
# MyClass.class_method()
# MyClass.static_method()
Most of these methods provide functionality specific to the data type they work with. They are key to creating efficient and readable Python programs.