__init__
__ 表示此函数方法不可篡改
self 和java/cpp里的this指针一样(基本上)
其他一点点积累
–
–
–
–
–
–
–
–
AI:
Sure, let’s dive into some of the unique aspects of Python syntax and conventions, particularly focusing on special methods (often called “dunder” methods, short for “double underscore”), and other common idioms like self
.
Special Methods (Dunder Methods)
Special methods in Python are methods that have double underscores before and after their names. These methods are used to provide special functionality to classes and objects. Here are a few commonly used ones:
__init__(self, ...)
: This is the initializer method, similar to a constructor in C++ or Go. It is called when an instance of the class is created.
class MyClass:
def __init__(self, value):
self.value = value
__str__(self)
: This method is called by thestr()
built-in function and by theprint
function to compute the “informal” string representation of an object.
class MyClass:
def __init__(self, value):
self.value = value
def __str__(self):
return f"MyClass with value {self.value}"
__repr__(self)
: This method is called by therepr()
built-in function and is meant to provide an “official” string representation of an object that can ideally be used to recreate the object.
class MyClass:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"MyClass({self.value!r})"
__getitem__(self, key)
: This method allows an object to use the indexing syntax (obj[key]
).
class MyList:
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return self.items[index]
__setitem__(self, key, value)
: This method allows an object to use the assignment via indexing (obj[key] = value
).
class MyList:
def __init__(self):
self.items = []
def __setitem__(self, index, value):
self.items[index] = value
The self
Parameter
In Python, self
is a conventional name for the first parameter of instance methods. It refers to the instance on which the method is called. This is somewhat similar to the this
pointer in C++.
class MyClass:
def __init__(self, value):
self.value = value
def display(self):
print(self.value)
Other Common Idioms
- Indentation: Python uses indentation to define blocks of code. This is unlike C++ or Go, where braces
{}
are used.
if x > 0:
print("Positive")
else:
print("Non-positive")
- List Comprehensions: A concise way to create lists.
squares = [x**2 for x in range(10)]
- Decorators: Functions that modify the behavior of other functions or methods.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
- Context Managers: Using
with
statements to manage resources.
with open('file.txt', 'r') as file:
content = file.read()
Example Class
Here is a complete example that incorporates some of these elements:
class MyClass:
def __init__(self, name, value):
self.name = name
self.value = value
def __str__(self):
return f"MyClass(name={self.name}, value={self.value})"
def __repr__(self):
return f"MyClass({self.name!r}, {self.value!r})"
def display(self):
print(f"Name: {self.name}, Value: {self.value}")
def __getitem__(self, index):
if index == 0:
return self.name
elif index == 1:
return self.value
else:
raise IndexError("Index out of range")
# Usage
obj = MyClass("example", 42)
print(obj) # Uses __str__
print(repr(obj)) # Uses __repr__
obj.display()
print(obj[0]) # Uses __getitem__
This should give you a good starting point for understanding Python syntax and some of its unique features.