首页 > 解决方案 > 访问类之间的变量

问题描述

我正在尝试创建一个“房地产”程序,其中每个代理都有一个属性列表。这些房产可以是公寓或房屋,每个房产都可以出租或购买。我无法打印每个代理的属性列表。我可以访问代理类中的“地址”属性,但无法访问其他属性。我也很难访问存储在其他类中的属性(购买价格/租赁价格)。我试图将它们作为全局变量传递,但它似乎不起作用。

给我带来麻烦的代理类在我的代码的底部。我对面向对象编程非常陌生,感谢您提供任何帮助。谢谢

# ======== Property class
class Property():

    def __init__(self, square_feet, num_bedrooms, num_bathrooms):
        super().__init__()
        self.square_feet = square_feet
        self.num_bedrooms = num_bedrooms
        self.num_bathrooms = num_bathrooms

    def prompt_init(self):
        pass

    def display(self):
        print(f'This {self.square_feet} square foot property '
              f'has {self.num_bedrooms} bedroom(s) '
              f'and {self.num_bathrooms} bathroom(s)')

# ======= House class
class House(Property):

    def __init__(self, square_feet, num_bedrooms, num_bathrooms,
                 num_stories, garage, fenced_yard):
        super().__init__(square_feet, num_bedrooms, num_bathrooms)
        self.num_stories = num_stories
        self.garage = garage
        self.fenced_yard = fenced_yard

    def display(self):
        super().display()
        print(f'This property is a house\n'
              f'Number of stories: {self.num_stories}\n'
              f'Garage included: {self.garage}\n'
              f'Fenced in yard: {self.fenced_yard}')

    @classmethod
    def prompt_init(self):
        square_feet = input("How many square feet is the property?: ")
        num_bedrooms = input("How many bedrooms?: ")
        num_bathrooms = input("How many bathrooms?: ")
        num_stories = input("How many stories?: ")
        garage = input ("Is there a garage?: ")
        fenced_yard = input("Is there a fenced yard?: ")
        return self(square_feet, num_bedrooms, num_bathrooms,
                    num_stories, garage, fenced_yard)

# ======== Apartment class
class Apartment(Property):

    def __init__(self, square_feet, num_bedrooms, num_bathrooms, balcony, laundry):
        super().__init__(square_feet, num_bedrooms, num_bathrooms)
        self.balcony = balcony
        self.laundry = laundry

    def display(self):
        super().display()
        print(f'This property is an apartment\n'
              f'Balcony included: {self.balcony}\n'
              f'Laundry included: {self.laundry}')

    @classmethod
    def prompt_init(self):
        square_feet = input("How many square feet is the property?: ")
        num_bedrooms = input("How many bedrooms?: ")
        num_bathrooms = input("How many bathrooms?: ")
        balcony = input("Is there a balcony?: ")
        laundry = input("Is there laundry?: ")
        return self(square_feet, num_bedrooms, num_bathrooms,
                    balcony, laundry)

# ======== Purchase class
class Purchase:

    def __init__(self, price, taxes):
        super().__init__()
        self.price = price
        self.taxes = taxes

    def display(self):
        super().display()
        print(f'This property is for sale\n'
              f'Price: {self.price}\n'
              f'Property Taxes: {self.taxes}\n')

    @classmethod
    def prompt_init(self):
        global price
        price = input("What is the listing price?: ")
        taxes = input("What is the annual property tax?: ")
        return self(price, taxes)

# ======== Rental class
class Rental:

    def __init__(self, furnished, utilities, rent2):
        super().__init__()
        self.furnished = furnished
        self.utilities = utilities
        self.rent = rent2

    def display(self):
        super().display()
        print(f'This property is a rental\n'
              f'Monthly rent: {self.rent}\n'
              f'Utilities: {self.utilities}\n'
              f'Furnished or Unfurnished: {self.furnished}')

    @classmethod
    def prompt_init(self):
        global rent
        rent = input("What is the monthly rent?: ")
        utilities = input("What are the monthly utilities?: ")
        furnished = input("Is the rental furnished?: ")
        return self(rent, utilities, furnished)

# ======== Listing Type Classes
class ApartmentRental(Apartment, Rental):

    def __init__(self):
        super().__init__(Apartment, Rental)

    @staticmethod
    def prompt_init():
        prompt1 = Apartment.prompt_init()
        prompt2 = Rental.prompt_init()
        return prompt1, prompt2

class ApartmentPurchase(Apartment, Purchase):

    def __init__(self):
        super().__init__(Apartment, Purchase)

    @staticmethod
    def prompt_init():
        prompt1 = Apartment.prompt_init()
        prompt2 = Purchase.prompt_init()
        return prompt1, prompt2

class HouseRental(House, Rental):
    def __init__(self):
        super().__init__(House, Rental)

    @staticmethod
    def prompt_init():
        prompt1 = House.prompt_init()
        prompt2 = Rental.prompt_init()
        return prompt1, prompt2

class HousePurchase(House, Purchase):
    def __init__(self):
        super().__init__(House, Purchase)

    @staticmethod
    def prompt_init():
        prompt1 = House.prompt_init()
        prompt2 = Purchase.prompt_init()
        return prompt1, prompt2

# ======== Agent class
class Agent():

    agentlist = []

    def __init__(self):
        self.properties = []

    listing_type = {tuple(['apartment', 'rental']): ApartmentRental,
                    tuple(['apartment', 'purchase']): ApartmentPurchase,
                    tuple(['house', 'rental']): HouseRental,
                    tuple(['house', 'purchase']): HousePurchase}

    def add_property(self):
        if Agent not in self.agentlist:
            self.agentlist.append(self)
        address = input("What is the property street address?: ")
        property_type = input("Is this property a house or apartment?: ").lower()
        purchase_type = input("Is this property a rental or a purchase?: ").lower()
        listing_class = self.listing_type[(property_type, purchase_type)]
        type = listing_class.prompt_init()
        self.properties.append(address)
        self.properties.append(property_type)
        self.properties.append(purchase_type)
        global rent
        global price
        var1 = rent
        var2 = price
        if purchase_type == "rental":
            self.properties.append(var1)
        elif purchase_type == "purchase":
            self.properties.append(var2)

    def list_properties(self):

# ====== prints list of objects
        for i in range(len(Agent.agentlist)):
            print(self.properties[i])

# ====== doesn't work
#        newlist = []
#        for i in range(len(Agent.agentlist)):
#            newlist.append(self.properties[i])
#            print(newlist)


rent = ''
price = ''

agent1 = Agent()
property1 = Agent.add_property(agent1)

print("Agent1 properties:")
agent1.list_properties()

#agent2 = Agent()
#property2 = Agent.add_property(agent2)

标签: pythonoopinheritancemultiple-inheritance

解决方案


您有一个初始化的代理列表,然后在init中您有一个初始化的属性列表。你能澄清这两者之间的区别吗?agentlist 是代理列表吗?如果是这样,您将希望在类之外跟踪这一点,并仅列出已实例化的 Agent 对象(可能在 main 中)。似乎问题部分可能在此类方法中:

    def list_properties(self):

# ====== prints list of objects
        for i in range(len(Agent.agentlist)):
            print(self.properties[i])

由于您的代理列表也在类声明中定义,因此在类本身中运行实例化代理对象列表并不容易。

再说一次,我无法重现或理解确切的问题。正如评论者所说,这将有助于隔离存在问题的部分。


推荐阅读