class Person:
def __init__(self, age, work):
self.age = age
self.work = work
def displayPerson(self):
print ("Person age: ", self.age, "Person work: ", self.work)
pers1 = Person(24, "data scientist")
pers2 = Person(16, "artist")
pers1.displayPerson()
pers2.displayPerson()
check = input("Input an attribute tho check if it exists: ")
if check = "age":
hasattr(pers1, age)
elif check = "work":
hasattr(pers1, work)
else
print("False.")
uj5u.com熱心網友回復:
您需要將等號更改為兩個等號進行比較。一個等號用于賦值。如果要查看回傳值,則需要列印 hasattr 方法。
uj5u.com熱心網友回復:
當你想用來if比較某物是否是equals to別的東西時,你應該使用==insted of =。
如果使用=,則將值歸因于變數。
以下是一些比較器的串列:https ://www.pythonpool.com/python-comparators/
看看這是否有效:
if check == "age":
hasattr(pers1, age)
elif check == "work":
hasattr(pers1, work)
else
print("False.")
uj5u.com熱心網友回復:
比較用 2 個等號完成,一個用于賦值:check == "age"
但是條件不應該是用戶給出的值,而應該是hasattr
test_attr = input("Input an attribute tho check if it exists: ")
if hasattr(pers1, test_attr):
print("Person does have", test_attr)
else:
print("Person do not have", test_attr)
最好的做法是讓呼叫者代碼執行print, 并且類將實作自己的表示
class Person:
def __str__(self):
return f"Person: age={self.age} work={self.work}"
print(pers1) # Person: age=24 work=data scientist
print(pers2) # Person: age=16 work=artist
uj5u.com熱心網友回復:
==是關系運算子(用于檢查某事物是否等于另一個),=而是賦值運算子(用于賦值)。你應該在==這里使用而不是=.
hasattr 也將回傳一個布林值(True 或 False),因此您應該列印它而不僅僅是呼叫該函式。
if check == "age":
print(hasattr(pers1, age))
elif check == "work":
print(hasattr(pers1, work))
else
print("False.")
您還可以通過執行以下操作來改進您的代碼:
if (hasattr(pers1,check)):
print("True")
else:
print("False");
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/444577.html
上一篇:如果陳述句與。while回圈
