簡體   English   中英

從同一模塊中的另一個類訪問屬性?

[英]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 設置為TrueFalse ,但是如何? 我正在考慮更換??? 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM