Hướng dẫn how do you check if an object has no attribute python? - làm cách nào để kiểm tra xem một đối tượng không có thuộc tính python?

Bạn có thể sử dụng HasAttr () để kiểm tra xem một đối tượng hoặc lớp có thuộc tính trong Python không.hasattr() to check if an object or class has an attribute in Python.

Ví dụ: có lớp Person như hình dưới đây:Person class as shown below:

class Person:
    greeting = "Hello"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def test(self):
        print("Test")

Sau đó, bạn có thể sử dụng HasAttr () cho đối tượng p như được hiển thị bên dưới:hasattr() for p object as shown below:

p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))

Output:

greeting: True
name: True
age: True
gender: True
test: True
__init__: True
__str__: True
__module__: True

Và, bạn cũng có thể sử dụng HasAttr () trực tiếp cho lớp Person như hình dưới đây:hasattr() directly for Person class as shown below:

print("greeting:", hasattr(Person, 'greeting'))
print("name:", hasattr(Person, 'name'))
print("age:", hasattr(Person, 'age'))
print("gender:", hasattr(Person, 'gender'))
print("test:", hasattr(Person, 'test'))
print("__init__:", hasattr(Person, '__init__'))
print("__str__:", hasattr(Person, '__str__'))
print("__module__:", hasattr(Person, '__module__'))

Output:

greeting: True
name: False
age: False
gender: False
test: True
__init__: True
__str__: True
__module__: True

Vì mọi thứ trong Python là một đối tượng và các đối tượng có các thuộc tính (trường và phương thức), nên việc viết các chương trình có thể kiểm tra loại thuộc tính nào mà một đối tượng có. Ví dụ, một chương trình Python có thể mở một ổ cắm trên máy chủ và nó chấp nhận các tập lệnh Python được gửi qua mạng từ máy khách. Khi nhận được tập lệnh mới, chương trình Python phía máy chủ có thể kiểm tra hoặc chính xác hơn các đối tượng, mô-đun và chức năng nội tâm trong tập lệnh mới để quyết định cách thực hiện chức năng, đăng nhập kết quả và các tác vụ hữu ích khác nhau.

Hasattr so với Try-Except

Có hai cách để kiểm tra xem một đối tượng Python có thuộc tính hay không. Cách đầu tiên là gọi hàm tích hợp hasattr(object, name), trả về True nếu chuỗi ____10 là tên của một trong các thuộc tính của ____ 11,

p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
2 nếu không. Cách thứ hai là
p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
3 để truy cập một thuộc tính trong một
p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
1 và thực hiện một số chức năng khác nếu một
p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
5 được nâng lên.

.
>>> hasattr('abc', 'upper')
True
>>> hasattr('abc', 'lower')
True
>>> hasattr('abc', 'convert')
False
[/python]

And:

[Python] >>> thử: ... 'abc'.upper () ... ngoại trừ thuộc tính : ....
>>> try:
... 'abc'.upper()
... except AttributeError:
... print("abc does not have attribute 'upper'")
...
'ABC'
>>> try:
... 'abc'.convert()
... except AttributeError:
... print("abc does not have attribute 'convert'")
...
abc does not have attribute 'convert'
[/python]

Sự khác biệt giữa hai phong cách này là gì?

p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
6 thường được gọi là kiểu lập trình Python có tên "Nhìn trước khi bạn nhảy" (LByl) vì bạn kiểm tra xem một đối tượng có thuộc tính hay không trước khi bạn truy cập. Trong khi
p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
7 được gọi là "dễ dàng yêu cầu tha thứ hơn sự cho phép" (EAFP) vì bạn
p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
3 Truy cập thuộc tính trước và yêu cầu tha thứ trong khối
p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
9 thay vì xin phép như
p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
6.

Cách nào tốt hơn, sau đó? Chà, cả hai học thuyết đều có những người ủng hộ trung thành và cả hai phong cách dường như rất thành thạo để đối phó với bất kỳ thử thách lập trình trong thế giới thực. Đôi khi, thật hợp lý khi sử dụng LByl nếu bạn muốn đảm bảo một thuộc tính chắc chắn tồn tại và dừng thực thi nếu không. Ví dụ: bạn biết chắc chắn tại một điểm trong chương trình rằng

p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
1 được thông qua sẽ có thuộc tính con trỏ tệp hợp lệ mà mã sau có thể hoạt động. Mặt khác, việc sử dụng EAFP cũng có ý nghĩa nếu bạn biết một thuộc tính có thể không tồn tại tại một số điểm trong quá trình thực hiện chương trình. Ví dụ, một trình phát nhạc không thể đảm bảo tệp MP3 luôn luôn ở cùng một vị trí, bởi vì nó có thể bị xóa, sửa đổi hoặc di chuyển bởi người dùng bất cứ lúc nào. Trong trường hợp này, trình phát nhạc có thể
p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
3 truy cập tệp MP3 trước và thông báo cho người dùng rằng tệp không tồn tại trong khối
p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
9.

Hasattr vs __dict__

Mặc dù

p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
6 là một hàm tích hợp được thiết kế để kiểm tra xem thuộc tính có tồn tại trong một đối tượng hay không, đôi khi có thể chính xác hơn để kiểm tra
greeting: True
name: True
age: True
gender: True
test: True
__init__: True
__str__: True
__module__: True
5 của đối tượng cho sự tồn tại của một thuộc tính thay vì thực tế là
p = Person("John", 27)
p.gender = "Male"
print("greeting:", hasattr(p, 'greeting'))
print("name:", hasattr(p, 'name'))
print("age:", hasattr(p, 'age'))
print("gender:", hasattr(p, 'gender'))
print("test:", hasattr(p, 'test'))
print("__init__:", hasattr(p, '__init__'))
print("__str__:", hasattr(p, '__str__'))
print("__module__:", hasattr(p, '__module__'))
6 không quan tâm đến lý do tại sao thuộc tính được gắn vào một đối tượng trong khi bạn có thể muốn biết lý do tại sao một thuộc tính được gắn vào một đối tượng. Ví dụ, một thuộc tính có thể được gắn vào một đối tượng do lớp cha của nó thay vì chính đối tượng.

[Python] >>> Lớp A (đối tượng): ... foo = 1 ... >>> Lớp B (a): ... Pass ... >>> B = B () >>> Hasattr ( B, 'foo') Đúng >>> 'foo' trong b .__ dict__ false [/python]
>>> class A(object):
... foo = 1
...
>>> class B(A):
... pass
...
>>> b = B()
>>> hasattr(b, 'foo')
True
>>> 'foo' in b.__dict__
False
[/python]

Trong mã trước, vì lớp

greeting: True
name: True
age: True
gender: True
test: True
__init__: True
__str__: True
__module__: True
7 là một lớp con của lớp
greeting: True
name: True
age: True
gender: True
test: True
__init__: True
__str__: True
__module__: True
8, lớp
greeting: True
name: True
age: True
gender: True
test: True
__init__: True
__str__: True
__module__: True
7 cũng có thuộc tính "foo". Tuy nhiên, vì "foo" được kế thừa từ
greeting: True
name: True
age: True
gender: True
test: True
__init__: True
__str__: True
__module__: True
8,
print("greeting:", hasattr(Person, 'greeting'))
print("name:", hasattr(Person, 'name'))
print("age:", hasattr(Person, 'age'))
print("gender:", hasattr(Person, 'gender'))
print("test:", hasattr(Person, 'test'))
print("__init__:", hasattr(Person, '__init__'))
print("__str__:", hasattr(Person, '__str__'))
print("__module__:", hasattr(Person, '__module__'))
1 không chứa nó. Đôi khi, điều quan trọng là phải biết liệu một thuộc tính đến từ bản thân lớp của một đối tượng hay từ siêu lớp của các đối tượng.

Lời khuyên và đề xuất

  • p = Person("John", 27)
    p.gender = "Male"
    print("greeting:", hasattr(p, 'greeting'))
    print("name:", hasattr(p, 'name'))
    print("age:", hasattr(p, 'age'))
    print("gender:", hasattr(p, 'gender'))
    print("test:", hasattr(p, 'test'))
    print("__init__:", hasattr(p, '__init__'))
    print("__str__:", hasattr(p, '__str__'))
    print("__module__:", hasattr(p, '__module__'))
    
    6 tuân theo nguyên tắc gõ con vịt trong Python: Khi tôi thấy một con chim đi bộ như một con vịt và bơi như một con vịt và những con vịt như một con vịt, tôi gọi con chim đó là một con vịt.

    When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.

    Vì vậy, hầu hết thời gian bạn muốn sử dụng

    p = Person("John", 27)
    p.gender = "Male"
    print("greeting:", hasattr(p, 'greeting'))
    print("name:", hasattr(p, 'name'))
    print("age:", hasattr(p, 'age'))
    print("gender:", hasattr(p, 'gender'))
    print("test:", hasattr(p, 'test'))
    print("__init__:", hasattr(p, '__init__'))
    print("__str__:", hasattr(p, '__str__'))
    print("__module__:", hasattr(p, '__module__'))
    
    6 để kiểm tra xem một thuộc tính có tồn tại trong một đối tượng không.

  • p = Person("John", 27)
    p.gender = "Male"
    print("greeting:", hasattr(p, 'greeting'))
    print("name:", hasattr(p, 'name'))
    print("age:", hasattr(p, 'age'))
    print("gender:", hasattr(p, 'gender'))
    print("test:", hasattr(p, 'test'))
    print("__init__:", hasattr(p, '__init__'))
    print("__str__:", hasattr(p, '__str__'))
    print("__module__:", hasattr(p, '__module__'))
    
    7 và
    greeting: True
    name: True
    age: True
    gender: True
    test: True
    __init__: True
    __str__: True
    __module__: True
    
    5 có các trường hợp sử dụng riêng thực sự khá hẹp so với
    p = Person("John", 27)
    p.gender = "Male"
    print("greeting:", hasattr(p, 'greeting'))
    print("name:", hasattr(p, 'name'))
    print("age:", hasattr(p, 'age'))
    print("gender:", hasattr(p, 'gender'))
    print("test:", hasattr(p, 'test'))
    print("__init__:", hasattr(p, '__init__'))
    print("__str__:", hasattr(p, '__str__'))
    print("__module__:", hasattr(p, '__module__'))
    
    6. Vì vậy, có lợi khi giữ các trường hợp sử dụng đặc biệt này ở phía sau đầu để bạn sẽ nhận ra chúng trong quá trình mã hóa và sử dụng các thành ngữ thích hợp cho phù hợp.

Khi bạn đã học cách kiểm tra xem một đối tượng có thuộc tính trong Python không, hãy kiểm tra cách lấy thuộc tính từ một đối tượng.