Xin chào Trong một cuộc thi lập trình địa phương gần đây, có một vấn đề trong đó bạn phải xác định một lớp có các tham số giống như chuỗi và trả về tổng của chúng, ví dụ: :
>>> Chain[2.5][2][2][2.5] # sum
9
>>> Chain[3][1.5][2][3] # sum
9.5
Điều tốt nhất mà tôi có thể viết là mã này:
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
Nhưng loại trả lại là một lớp không phải là INT, hơn nữa tôi đang sử dụng một thuộc tính tĩnh rõ ràng là sai. Sẽ đánh giá cao bất kỳ sự giúp đỡ.
P.S. : Xin lưu ý rằng cuộc thi đó kết thúc vào ngày 7 tháng 1 năm 2022 vì vậy tôi không nghĩ có bất kỳ vấn đề nào với việc đăng câu hỏi này.
Shahpar KhanThe need for __str__ method:
The
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 method in Python represents the class objects as a string – it can be used for classes. The class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 method in Python represents the class objects as a string – it can be used for classes. The class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 method
should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.The
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 method is called when the following functions are invoked on the object and return a string:- print[]
- str[]
If we have not defined the
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3, then it will call the class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method. The class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method returns a string that describes the pointer of the object by default [if the programmer does not define it].class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method returns a string that describes the pointer of
the object by default [if the programmer does not define it].How to call __str__ method
1. Default implementation
class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject.__repr__[]] print[myObject]
The above code shows an example where neither
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 nor class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 are defined. Calling class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 calls the default class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method, and they all give the same output, the pointer of our object.2. Custom __str__ method
class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString def __str__ [self]: return 'MyClass[x=' + str[self.x] + ' ,y=' + self.y + ']' myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject] print[str[myObject]] print[myObject.__repr__[]]
The code above shows the output once you have defined the
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 method. When class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3, class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject.__repr__[]] print[myObject]5, or
class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject.__repr__[]] print[myObject]6 are called you will get your defined output. Make note that the
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 output remains the same.3. __repr__ method defined only
class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString def __repr__ [self]: return 'MyClass[x=' + str[self.x] + ' ,y=' + self.y + ']' myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject] print[str[myObject]] print[myObject.__repr__[]]
In the first example we saw that when
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 is not defined it automatically calls the class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method. Therefore, the output of all the functions - class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3, class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject.__repr__[]] print[myObject]6, and
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 - are the same. Moreover, the class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method does not necessarily need to return a string. In case it does not return a string, the class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject.__repr__[]] print[myObject]5 statements will throw an error.
CONTRIBUTOR
Shahpar Khan
The need for __str__ method:
The
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 method in Python represents the class objects as a string – it can be used for classes. The class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.The
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 method is called when the following functions are invoked on the object and return a string:# -----------------------------------------------------------
#Cafedev.vn - Kênh thông tin IT hàng đầu Việt Nam
#@author cafedevn
#Contact:
#Fanpage: //www.facebook.com/cafedevn
#Group: //www.facebook.com/groups/cafedev.vn/
#Instagram: //instagram.com/cafedevn
#Twitter: //twitter.com/CafedeVn
#Linkedin: //www.linkedin.com/in/cafe-dev-407054199/
#Pinterest: //www.pinterest.com/cafedevvn/
#YouTube: //www.youtube.com/channel/UCE7zpY_SlHGEgo67pHxqIoA/
# -----------------------------------------------------------
s = 'Hello, Cafedev.'
print str[s]
print str[2.0/11.0]
Kết quả in ra là:
Hello, Cafedev.
0.181818181818
If we have not defined the
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3, then it will call the class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method. The class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method returns a string that describes the pointer of the object by default [if the programmer does not define it].
s = 'Hello, Cafedev.'
print repr[s]
print repr[2.0/11.0]
Kết quả in ra là:
'Hello, Cafedev.'
0.18181818181818182
How to call __str__ method
1. Default implementation
The above code shows an example where neither
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 nor class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 are defined. Calling class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 calls the default class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method, and they all give the same output, the pointer of our object.2. Custom __str__ method
The code above shows the output once you have defined the
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 method. When class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3, class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject.__repr__[]] print[myObject]5, or
class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject.__repr__[]] print[myObject]6 are called you will get your defined output. Make note that the
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 output remains the same.3. __repr__ method defined only
import datetime
today = datetime.datetime.now[]
# Prints readable format for date-time object
print str[today]
# prints the official format of date-time object
print repr[today]
Kết quả in ra là:
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
0In the first example we saw that when
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3 is not defined it automatically calls the class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method. Therefore, the output of all the functions - class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
3, class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject.__repr__[]] print[myObject]6, and
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 - are the same. Moreover, the class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
7 method does not necessarily need to return a string. In case it does not return a string, the class MyClass: x = 0 y = "" def __init__[self, anyNumber, anyString]: self.x = anyNumber self.y = anyString myObject = MyClass[12345, "Hello"] print[myObject.__str__[]] print[myObject.__repr__[]] print[myObject]5 statements will throw an error.
CONTRIBUTOR
Copyright ©2022 Educative, Inc. All rights reserved
Cả hai hàm str[] và repr[] đều được sử dụng để lấy về dạng thức kiểu string của một đối tượng
Dưới đây là đoạn chương trình Python mô tả cách viết hàm__repr__ và hàm __str__ cho một class do người dùng tự định nghĩa.
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
1Kết quả in ra là:
class Chain[]:
value = 0
def __new__[self, num]:
self.value += num
return self
obj = Chain[2][3]
print[obj.value]
2Nguồn và Tài liệu tiếng anh tham khảo:
- w3school
- python.org
- geeksforgeeks
Tài liệu từ cafedev:
- Full series tự học Python từ cơ bản tới nâng cao tại đây nha.
- Ebook về python tại đây.
- Các series tự học lập trình khác
Nếu bạn thấy hay và hữu ích, bạn có thể tham gia các kênh sau của cafedev để nhận được nhiều hơn nữa:
- Group Facebook
- Fanpage
- Youtube
- Trang chủ
Chào thân ái và quyết thắng!