Python Forum
How to use global value or local value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use global value or local value
#5
(Jan-11-2023, 09:00 AM)sabuzaki Wrote: Let's say scenario: We have hundreds of houses each having different internet speed: 5Mbps/100Mbps/25Mbps (so we have a class for each house). Then we have rooms/people in each house. If that person/room has a faster internet speed (lets say room1 for the house5), that room/person should not use houses internet, it should use it's own faster internet.... (use room variable rather than global house variable)
In that scenario, Room/Person are not subclasses of House because their relation is not the IS-A relationship. A room is not a particular kind of house. In that case it is better to use aggregation. Each room will have a pointer to the house to which it belongs
class House:
    def __init__(self, speed):
        self.speed = speed

class Room:
    def __init__(self, house):
        self.house = house
        self._speed = 0

    @property
    def speed(self):
        return max(self._speed, self.house.speed)

    def update_speed(self, value):
        self._speed = value

    def delete_speed(self):
        self._speed = 0

h1 = House(5)
h2 = House(100)
r1 = Room(h2)
r2 = Room(h2)
print(r1.speed)
print(r2.speed)
r1.update_speed(500)
print(r1.speed)
print(r2.speed)
print(h2.speed)
r1.delete_speed()
print(r1.speed)
r1.update_speed(50)
print(r1.speed)
Output:
100 100 500 100 100 100 100
Reply


Messages In This Thread
RE: How to use global value or local value - by Gribouillis - Jan-11-2023, 11:59 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  It's saying my global variable is a local variable Radical 5 1,231 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Delete all Excel named ranges (local and global scope) pfdjhfuys 2 1,841 Mar-24-2023, 01:32 PM
Last Post: pfdjhfuys
  Global variables or local accessible caslor 4 1,068 Jan-27-2023, 05:32 PM
Last Post: caslor
  Global vs. Local Variables Davy_Jones_XIV 4 2,695 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  Global - local variables Motorhomer14 11 4,311 Dec-17-2020, 06:40 PM
Last Post: Motorhomer14
  from global space to local space Skaperen 4 2,359 Sep-08-2020, 04:59 PM
Last Post: Skaperen
  local / global lists RedWuff 1 1,901 May-26-2020, 03:11 AM
Last Post: deanhystad
  Question regarding local and global variables donmerch 12 5,188 Apr-12-2020, 03:58 PM
Last Post: TomToad
  local/global variables in functions abccba 6 3,474 Apr-08-2020, 06:01 PM
Last Post: jefsummers
  modifying variables in local or global space Skaperen 2 2,243 Aug-14-2019, 07:13 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020