You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在跨模块的Person类中访问Friend类的first属性?

问题分析与修复方案

嘿,作为OOP新手碰到这种属性访问问题很正常,咱们先拆解你代码里的问题,再一步步解决:

1. 你当前代码的核心问题

你写的Friend.first是错的——因为first是Friend类的实例属性(在__init__里用self.first定义的,属于每个具体的Friend对象),不是类属性(属于整个Friend类的),所以不能直接用类名去访问。另外,你的Person继承了Friend,但没在自己的__init__里调用父类的初始化方法,导致Person实例根本没继承到Friend的那些属性。

2. 分两种场景解决

场景一:访问当前Person实例自己的first属性(继承自Friend)

既然Person继承了Friend,那只要正确初始化父类,Person实例自己就会有first属性。修改代码如下:

修正后的persons.py

from friends import Friend

class Person(Friend):
    def __init__(self, firstname, lastname):
        # 调用父类的初始化方法,把参数传进去,这样父类的属性会被初始化
        super().__init__(firstname, lastname)
        # 其实下面这两行可以省略,因为父类已经把firstname存到self.first,lastname存到self.last了
        self.firstname = firstname
        self.lastname = lastname

    def to_print(self):
        # 直接访问当前实例的first属性(来自父类Friend)
        print(self.first)
        print(self.last)

对应main.py

from persons import Person
from friends import Friend

P = Person("Alex", "Something")
F = Friend("Arthur", "Whatever")

P.to_print()  # 会输出Alex和Something

场景二:访问另一个独立的Friend实例的first属性

如果你想在Person的方法里访问某个特定的Friend对象(比如main里的F),有两种常见方式:

方式一:调用方法时传入Friend实例

修改persons.py的to_print:

from friends import Friend

class Person(Friend):
    def __init__(self, firstname, lastname):
        super().__init__(firstname, lastname)

    def to_print(self, friend):
        print(self.first)
        # 访问传入的Friend实例的first属性
        print(friend.first)

然后main.py里这么调用:

from persons import Person
from friends import Friend

P = Person("Alex", "Something")
F = Friend("Arthur", "Whatever")

P.to_print(F)  # 输出Alex和Arthur

方式二:实例化Person时绑定Friend实例

from friends import Friend

class Person(Friend):
    def __init__(self, firstname, lastname, friend):
        super().__init__(firstname, lastname)
        self.my_friend = friend  # 把Friend实例存到Person里

    def to_print(self):
        print(self.first)
        print(self.my_friend.first)

main.py里:

from persons import Person
from friends import Friend

F = Friend("Arthur", "Whatever")
# 实例化Person时把F传进去
P = Person("Alex", "Something", F)

P.to_print()  # 输出Alex和Arthur

小提醒:避免循环导入

你现在的代码里persons.py导入Friend,friends.py没导入Person,所以不会有循环导入的问题。以后如果需要双向导入,记得把导入放在函数内部(延迟导入),或者调整模块结构哦。

内容的提问来源于stack exchange,提问作者Alexander2512

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:12:34