gpt4 book ai didi

python - 如何从Python中的单个类继承一个类的多个实例

转载 作者:行者123 更新时间:2023-12-01 06:43:58 24 4
gpt4 key购买 nike

免责声明:我是编程新手,刚刚开始学习类和继承,所以也许是我缺乏理解导致了我的问题?

我在单独的文件 person.pyaddress.py 中创建了两个类。

人员类继承自地址类,但是一个人可以有多个地址(邮政地址、实际地址等)。我如何为每种类型继承地址类的多个实例。

我的目标是最终为 future 的项目建立一个公共(public)类库,因此非常感谢有关此概念的任何帮助或建设性意见。

我希望能够创建类似下面的代码,其中邮政地址和物理地址都使用 Address 类:

employee = Person()
employee.set_postal_address("342 Gravelpit Terrace","Bedrock")
employee.set_physical_address("742 Evergreen Tce", "Springfield")

下面是我的代码,我没有在 Person() 类中创建对 Address() 的任何引用,因为我不确定如何实现这一点?

# address.py

class Address:
def __init__(self):
self.__line1 = None
self.__line2 = None
self.__town_city = None
self.__post_code = None
self.__state_region = None
self.__country = None

# Line 1
def get_line1(self):
return self.__line1

def set_line1(self, line1):
self.__line1 = line1

#etc....
# person.py

from address import *

class Person(Address):

def __init__(self):
self.__first_name = None
self.__last_name = None
self.__postal_address = []
self.__physical_adress = []


def set_postal_address(self):
# use the address class
# return a list of address values
self.__postal_address = []

def set_physical_address(self):
# use the address class
# return a list of address values
self.__physical_address = []

#etc...

非常感谢任何帮助。如果有更好的方法来处理这个问题请告诉我。

最佳答案

创建Person类时,您不一定需要继承Address。实现目标的一种方法是在 Person 类中初始化一个 Address 类对象。

# address.py

class Address:
def __init__(self, **kwargs):
self.__line1 = kwargs.get('__line1')
self.__line2 = kwargs.get('__line2')
self.__town_city = kwargs.get('__town_city')
self.__post_code = kwargs.get('__post_code')
self.__state_region = kwargs.get('__state_region')
self.__country = kwargs.get('__country')

# Line 1
def get_line1(self):
return self.__line1

def set_line1(self, line1):
self.__line1 = line1

#etc....
# person.py

from address import *

class Person:

def __init__(self, **kwargs):
self.__first_name = kwargs.get('__first_name')
self.__last_name = kwargs.get('__last_name')
self.__postal_address = None
self.__physical_address = None


def set_postal_address(self, **kwargs):
# use the address class
self.__postal_address = Address(**kwargs)

def set_physical_address(self, **kwargs):
# use the address class
self.__physical_address = Address(**kwargs)

#etc...

这允许您防止继承的方法在给定的类对象中变得困惑,但仍然允许您保持良好的类结构。

然后你可以这样做:

bob=Person(__first_name='Bob', __last_name='Smith')
bob.set_postal_address(__line1='42 Wallaby Way', __town_city='Sydney')
# Since we are using kwargs.get() any not specified Kwarg comes out as None.
# Now `__postal_address` is its own Address class and comes with Address methods
bob.__postal_address.set__line2('Apt 3B')

现在有时您希望从更高级别的类继承通用方法。您可以在此处阅读有关 python 类的更多信息:( https://docs.python.org/3.6/tutorial/classes.html )

关于python - 如何从Python中的单个类继承一个类的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59329157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com