![](/img/trans.png)
[英]How to access a class attribute based on the value of another attribute of the same class?
[英]Access attribute from another class in the same module?
假設我有 person.py,它看起來像這樣:
class Eyes:
def __init__(self, color):
self.color = color
class Head:
def __init__(self, size):
self.have_dark_eyes = ???
self.size = size
然后:
import person
eyes = person.Eyes("blue")
head = person.Head("small")
if (head.has_dark_eyes == True):
...
我想使用屬性color
將 have_dark_eyes 設置為True
或False
,但是如何? 我正在考慮更換???
True if color == "brown" else False
但它不起作用。
謝謝。
您至少必須為Head
提供一個Eyes
實例,例如類似的東西
class Eyes:
def __init__(self, color):
self.color = color
class Head:
def __init__(self, eyes, size):
self.have_dark_eyes = eyes.color == 'brown'
self.size = size
用法示例:
dark_eyes = Eyes('brown')
head = Head(dark_eyes, 10)
print(head.have_dark_eyes) # Prints True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.