Hướng dẫn can you print objects in python? - bạn có thể in các đối tượng trong python không?

Khi tôi cố gắng

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
6 một thể hiện của một lớp, tôi sẽ nhận được một đầu ra như thế này:

>>> class Test():
...     def __init__(self):
...         self.a = 'foo'
...
>>> print(Test())
<__main__.Test object at 0x7fc9a9e36d60>

Làm thế nào tôi có thể xác định hành vi in ​​(hoặc biểu diễn chuỗi) của một lớp và các trường hợp của nó? Ví dụ: tham khảo mã trên, làm thế nào tôi có thể sửa đổi lớp

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
7 để
class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
6ing một thể hiện hiển thị giá trị
class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
9?

Hướng dẫn can you print objects in python? - bạn có thể in các đối tượng trong python không?

Karl Knechtel

59.4K10 Huy hiệu vàng86 Huy hiệu bạc132 Huy hiệu đồng10 gold badges86 silver badges132 bronze badges

Hỏi ngày 8 tháng 10 năm 2009 lúc 2:35Oct 8, 2009 at 2:35

Hướng dẫn can you print objects in python? - bạn có thể in các đối tượng trong python không?

Ashwin Nanjappaashwin NanjappaAshwin Nanjappa

74K79 Huy hiệu vàng208 Huy hiệu bạc291 Huy hiệu Đồng79 gold badges208 silver badges291 bronze badges

0

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

Phương pháp

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
0 là những gì được gọi là xảy ra khi bạn in nó và phương thức
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 là những gì xảy ra khi bạn sử dụng hàm
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
2 (hoặc khi bạn nhìn vào nó với lời nhắc tương tác).

Nếu không có phương thức

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
0 được đưa ra, Python sẽ in kết quả của
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 thay thế. Nếu bạn xác định
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
0 nhưng không phải
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1, Python sẽ sử dụng những gì bạn thấy ở trên là
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1, nhưng vẫn sử dụng
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
0 để in.

Đã trả lời ngày 8 tháng 10 năm 2009 lúc 2:39Oct 8, 2009 at 2:39

Chris Lutzchris LutzChris Lutz

71.5K16 Huy hiệu vàng126 Huy hiệu bạc182 Huy hiệu Đồng16 gold badges126 silver badges182 bronze badges

7

Như Chris Lutz giải thích, điều này được xác định bằng phương pháp

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 trong lớp của bạn.

Từ tài liệu của

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
2:

Đối với nhiều loại, hàm này cố gắng trả về một chuỗi sẽ mang lại một đối tượng có cùng giá trị khi được chuyển đến

def __repr__(self):
    cls = self.__class__
    return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
1, nếu không, biểu diễn là một chuỗi được đặt trong các khung góc chứa tên của loại đối tượng cùng với Thông tin thường bao gồm tên và địa chỉ của đối tượng. Một lớp có thể kiểm soát những gì hàm này trả về cho các trường hợp của nó bằng cách xác định phương thức
def __repr__(self):
    cls = self.__class__
    return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
2.

Đưa ra bài kiểm tra lớp sau:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"

.. nó sẽ hành động theo cách sau trong vỏ Python:

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456

Nếu không có phương thức

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
0 được xác định,
def __repr__(self):
    cls = self.__class__
    return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
4 (hoặc
def __repr__(self):
    cls = self.__class__
    return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
5) sẽ sử dụng kết quả của
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 thay thế

Nếu không có phương thức

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 được xác định thì mặc định được sử dụng, tương đương với:

def __repr__(self):
    cls = self.__class__
    return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"

Karl Knechtel

59.4K10 Huy hiệu vàng86 Huy hiệu bạc132 Huy hiệu đồng10 gold badges86 silver badges132 bronze badges

Hỏi ngày 8 tháng 10 năm 2009 lúc 2:35Oct 8, 2009 at 2:55

7

Ashwin Nanjappaashwin Nanjappa

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)

74K79 Huy hiệu vàng208 Huy hiệu bạc291 Huy hiệu Đồng

elem = Element('my_name', 'some_symbol', 3)
print(elem)

Phương pháp

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
0 là những gì được gọi là xảy ra khi bạn in nó và phương thức
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 là những gì xảy ra khi bạn sử dụng hàm
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
2 (hoặc khi bạn nhìn vào nó với lời nhắc tương tác).

__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}

Nếu không có phương thức

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
0 được đưa ra, Python sẽ in kết quả của
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 thay thế. Nếu bạn xác định
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
0 nhưng không phải
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1, Python sẽ sử dụng những gì bạn thấy ở trên là
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1, nhưng vẫn sử dụng
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
0 để in.Sep 17, 2015 at 16:35

user394430user394430user394430

Đã trả lời ngày 8 tháng 10 năm 2009 lúc 2:392 gold badges26 silver badges27 bronze badges

0

Chris Lutzchris Lutz

print(a.__dict__)

71.5K16 Huy hiệu vàng126 Huy hiệu bạc182 Huy hiệu Đồng

Như Chris Lutz giải thích, điều này được xác định bằng phương pháp

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 trong lớp của bạn.Oct 25, 2018 at 22:25

Từ tài liệu của

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
2:John

Đối với nhiều loại, hàm này cố gắng trả về một chuỗi sẽ mang lại một đối tượng có cùng giá trị khi được chuyển đến

def __repr__(self):
    cls = self.__class__
    return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
1, nếu không, biểu diễn là một chuỗi được đặt trong các khung góc chứa tên của loại đối tượng cùng với Thông tin thường bao gồm tên và địa chỉ của đối tượng. Một lớp có thể kiểm soát những gì hàm này trả về cho các trường hợp của nó bằng cách xác định phương thức
def __repr__(self):
    cls = self.__class__
    return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
2.8 silver badges11 bronze badges

4

Đưa ra bài kiểm tra lớp sau:

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return  str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))

elem = Element('my_name', 'some_symbol', 3)
print(elem)

.. nó sẽ hành động theo cách sau trong vỏ Python:

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
0

Nếu không có phương thức

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
0 được xác định,
def __repr__(self):
    cls = self.__class__
    return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
4 (hoặc
def __repr__(self):
    cls = self.__class__
    return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
5) sẽ sử dụng kết quả của
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 thay thế

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
1

Nếu không có phương thức

>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 được xác định thì mặc định được sử dụng, tương đương với:Mar 14, 2018 at 15:44

Hướng dẫn can you print objects in python? - bạn có thể in các đối tượng trong python không?

1

Đã trả lời ngày 8 tháng 10 năm 2009 lúc 2:55

Một cách chung có thể được áp dụng cho bất kỳ lớp nào mà không có định dạng cụ thể có thể được thực hiện như sau:

Và sau đó,

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
2

sản xuấtMay 20, 2016 at 14:26

Đã trả lời ngày 17 tháng 9 năm 2015 lúc 16:35PeterM

2.6652 huy hiệu vàng26 Huy hiệu bạc27 Huy hiệu đồng24 silver badges35 bronze badges

1

Nếu bạn đang ở trong một tình huống như @Keith, bạn có thể thử:

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
3

Nó đi ngược lại những gì tôi sẽ xem xét phong cách tốt nhưng nếu bạn chỉ cố gắng gỡ lỗi thì nó sẽ làm những gì bạn muốn.

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
4

Đã trả lời ngày 25 tháng 10 năm 2018 lúc 22:25Jan 27, 2021 at 17:01

JohnjohnAlon

1.5798 huy hiệu bạc11 huy hiệu đồng2 silver badges8 bronze badges

1

Phiên bản phản hồi đẹp hơn của @user394430

Sản xuất danh sách trực quan của các tên và giá trị.

Một phiên bản thậm chí fancier (cảm ơn Ruud) sắp xếp các mục:

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
5

Đã trả lời ngày 14 tháng 3 năm 2018 lúc 15:44

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
6

Cho Python 3:

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
7

Nếu định dạng cụ thể không quan trọng (ví dụ: để gỡ lỗi) chỉ kế thừa từ lớp có thể in bên dưới. Không cần phải viết mã cho mọi đối tượng.

Lấy cảm hứng từ câu trả lời nàyDec 20, 2012 at 11:27

Đã trả lời ngày 20 tháng 5 năm 2016 lúc 14:26tnotstar

Petermpeterm1 gold badge16 silver badges26 bronze badges

2.19224 huy hiệu bạc35 huy hiệu đồng

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
8

Giản dị. Trong bản in, làm:

miễn là hàm tạo là17 gold badges228 silver badges301 bronze badges

Đã trả lời ngày 27 tháng 1 năm 2021 lúc 17:01Jan 16, 2013 at 9:04

flow_chartflow_chartflow_chart

Alonalon1 silver badge4 bronze badges

1

1612 Huy hiệu bạc8 Huy hiệu đồng

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
9

Chỉ để thêm hai xu của tôi vào câu trả lời của @DBR, sau đây là một ví dụ về cách thực hiện câu này từ tài liệu chính thức mà anh ấy đã trích dẫn:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
0

"[...] để trả về một chuỗi sẽ mang lại một đối tượng có cùng giá trị khi được chuyển đến eval (), [...]" "Mar 13, 2021 at 0:59

Hướng dẫn can you print objects in python? - bạn có thể in các đối tượng trong python không?

Đưa ra định nghĩa lớp này:minker

Bây giờ, rất dễ để tuần tự hóa thể hiện của lớp

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
7:4 silver badges3 bronze badges

Vì vậy, chạy đoạn mã cuối cùng, chúng tôi sẽ nhận được:

Bạn chỉ cần đảm bảo rằng bạn có dấu ngoặc đơn ở cuối lớp, ví dụ:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
1

Đây là một ví dụ về mã từ một dự án tôi đang thực hiện:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
2

Để in lớp hydro của tôi, tôi đã sử dụng như sau:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
3

Xin lưu ý, điều này sẽ không hoạt động mà không có dấu ngoặc đơn ở cuối hydro. Họ là cần thiết.

Hy vọng điều này sẽ giúp, hãy cho tôi biết nếu bạn có câu hỏi nữa.

Đã trả lời ngày 4 tháng 8 năm 2015 lúc 4:52Aug 4, 2015 at 4:52

Mặc dù đây là một bài viết cũ hơn, nhưng cũng có một phương pháp rất thuận tiện được giới thiệu trong các dữ liệu (như Python 3.7). Bên cạnh các chức năng đặc biệt khác như

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)
7 và
class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)
8, nó cung cấp hàm
>>> t = Test(123, 456)
>>> t

>>> print(repr(t))

>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
1 cho các thuộc tính lớp. Ví dụ của bạn sau đó sẽ là:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
4

Nếu bạn muốn ẩn một thuộc tính nhất định khỏi được xuất ra, bạn có thể đặt tham số Trình trang trí trường

elem = Element('my_name', 'some_symbol', 3)
print(elem)
0 thành
elem = Element('my_name', 'some_symbol', 3)
print(elem)
1:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f""

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"
5

Đã trả lời ngày 24 tháng 8 lúc 14:54Aug 24 at 14:54

Hướng dẫn can you print objects in python? - bạn có thể in các đối tượng trong python không?

Dheinzdheinzdheinz

8229 Huy hiệu bạc15 Huy hiệu Đồng9 silver badges15 bronze badges

Điều gì xảy ra khi đối tượng được in python?

Hàm in () in thông báo được chỉ định lên màn hình hoặc thiết bị đầu ra tiêu chuẩn khác.Thông báo có thể là một chuỗi hoặc bất kỳ đối tượng nào khác, đối tượng sẽ được chuyển đổi thành một chuỗi trước khi được ghi vào màn hình.the object will be converted into a string before written to the screen.

Bạn có thể in những gì trong Python?

Hàm in () trong Python được sử dụng để in một thông báo được chỉ định trên màn hình.Lệnh in trong Python in các chuỗi hoặc các đối tượng được chuyển đổi thành một chuỗi trong khi in trên màn hình.a specified message on the screen. The print command in Python prints strings or objects which are converted to a string while printing on a screen.

Đối tượng trong Python là gì?

Một đối tượng là một thể hiện của một lớp.Một lớp giống như một bản thiết kế trong khi một thể hiện là bản sao của lớp có giá trị thực.Python là ngôn ngữ lập trình hướng đối tượng nhấn mạnh trên các đối tượng, tức là nó chủ yếu nhấn mạnh các chức năng.an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. Python is object-oriented programming language that stresses on objects i.e. it mainly emphasizes functions.