Python 嵌套内部类 - 对象编程 [重复]

问题描述 投票:0回答:2

我想了解 Python 类和对象。

我正在努力并努力从内部类中获取输出结果,

Features

class Person:
    def __init__(self):
        pass

    def first_name(self, first_name ):
        self.first_name = first_name
        return self.first_name

    def middle_name(self, middle_name):
        self.middle_name = middle_name

    def last_name(self, last_name):
        self.last_name = last_name
        return self.last_name

    class Features:
        def __init__(self):
            pass
        def color(self, color):
            self.color = color
            return self.color

x = Person()
print(x.last_name('Jimmy'))

print(x.Features.color('Brown'))

相反,我收到此错误:

TypeError:Person.Features.color() 缺少 1 个必需的位置参数:'color'

我怎样才能正确地做到这一点?

python class object inner-classes
2个回答
1
投票

我个人不会像这样嵌套类,但如果您出于某种原因想这样做,这是向前迈出的第一步。这里的关键是,作为人

__init__()
的一部分,我们
__init__()
他们的特征。

class Person:
    class Features:
        def __init__(self, color=None):
            self.color = color

    def __init__(self, first, middle, last):
        self.first_name = first
        self.middle_name = middle
        self.last_name = last
        self.features = Person.Features()

    def __str__(self):
        return f"{self.last_name}, {self.first_name}\n\tHair Color: {self.features.color}"

person = Person("Jane", "Mary", "Doe")
person.first_name="Sara"
person.features.color = "Red"
print(person)

这应该给你:

Doe, Sara
        Hair Color: Red

您还可以探索使用 getter 和 setter 的 Python 方式是什么?


0
投票

你的内部类是另一个类定义,就像外部类一样。

a_person = Person()
a_feature = Person.Features()

要使用它,您需要定义它。

x = Person()
print(x.last_name('Jimmy'))
y = x.Features() # Or just Person.Features()
print(y.color('Brown'))

以及错误原因:

missing 1 required positional argument

这是因为您试图在不初始化 Features 类的情况下调用

color()
函数。这意味着
self
参数(它引用现在不存在的初始化类)不会传递给
color
函数。

所以它给你错误,因为它把你的

"Brown"
作为
self
参数,所以没有给
color
参数提供任何东西;因此:

Person.Features.color() missing 1 required positional argument: 'color'
© www.soinside.com 2019 - 2024. All rights reserved.