0

not sure if this question has been asked before, maybe the way that I've been wording the question is wrong but here goes,

Suppose I have the code below:

class House:

    def __init__(self):
        self.living_room = "living_room"
        self.bed_room = "bed_room"
        self.garage = "garage"

def test(house,room):
   print(house.room) #I know I can't write it this way, but just as an example of what I'm hoping to achieve

I want to pass in the property of the House class to the function test for the arguement room such that if room is garage then the test function prints out "garage" and if room is bed_room then "bed_room" gets printed out. Is there a way of achieving this? I prefer not to have multiple functions doing the same thing apart from accessing different properties of the class. Thanks

Mark
  • 730
  • 1
  • 8
  • 22

2 Answers2

0

To get a class attribute you can use __getattribute__ method. Also, you should have already created class instance:

class House:
    def __init__(self):
        self.living_room = "living_room"
        self.bed_room = "bed_room_property"
        self.garage = "garage"

my_house = House()

def test(house,room):
   print(house.__getattribute__(room))

test(my_house, 'bed_room')

Output:

bed_room_property
Alex
  • 798
  • 1
  • 8
  • 21
  • `__getattribute__` is only part of attribute resolution. The `getattr` function is the tool to use here. – user2357112 Dec 03 '20 at 07:48
  • @user2357112supportsMonica That's true, but anyway `getattr()` calls `__getattribute__` – Alex Dec 03 '20 at 07:52
  • 1
    `__getattribute__` is *one* of the things `getattr` calls. It also tries `__getattr__`. `__getattribute__` is not responsible for performing the `__getattr__` fallback, and directly calling `__getattribute__` will fail to find attributes implemented through `__getattr__`. – user2357112 Dec 03 '20 at 07:53
0
class House:

    def __init__(self):
        self.living_room = "living_room"
        self.bed_room = "bed_room"
        self.garage = "garage"

# In order to use the class properties an object must be created

a=House()#Here a is the object of the class House

def test(room):
    print(room)


#The function test is called with the parameter

test(a.living_room)#In a.living_room a is the object,living_room is attribute of House

#Likewise you can call the other attributes of the class and print it with the 
function test