0

I am reading to some piece of code written by some experienced programmer, and I do not understand some part of it. Unfortunately, I am new to Python programming.

This is the line of code which confuses me:

realworld = ConcreteRealWorldScheduler(RealWorldScenario(newscenario)).schedule()

To generalize I will rewrite it again

variable = OneConcreteClass(OneClass(anotherVariable)).method()

This part confuses me the most:

(RealWorldScenario(newscenario))

If someone could give me a thorough description it would be very helpful.

THanks

Kristof Pal
  • 966
  • 4
  • 12
  • 28

4 Answers4

4

This is the same as:

# New object, newscenario passed to constructor
world_scenario = RealWordScenario(newscenario)
# Another new object, now world_scenario is passed to constructor
scheduler = ConcreteRealWorldScheduler(world_scenario)
# Call the method
variable = scheduler.method()
Aleph
  • 1,209
  • 10
  • 19
1

It may seem confusing due to the naming, or the complexity of the classes, but this is essentially the same as:

foo = set(list('bar')).pop()

So, in this example:

  1. First of all a list is being instantiated with 'bar'
    • list('bar') == ['b', 'a', 'r']
  2. Next a set is created from the list
    • set(['b', 'a', 'r']) == {'a', 'b', 'r'}
  3. Then we use set's the pop() method
    • {'a', 'b', 'r'}.pop() will return 'a' and leave the set as {'b', 'r'}

So the same is true of your given line of code:

realworld = ConcreteRealWorldScheduler(RealWorldScenario(newscenario)).schedule()
  1. First a new RealWorldScenario is instantiated with newscenario
  2. Next, a ConcreteRealWorldScheduler is instantiated with the RealWorldScenario instance
  3. Finally, the schedule() method of the ConcreteRealWorldScheduler instance is called.
Josha Inglis
  • 1,018
  • 11
  • 23
0

Working from the outside instead, we have

variable = OneConcreteClass(OneClass(anotherVariable)).method()

or

variable = SomethingConfusing.method()

We conclude SomethingConfusing is an object with a method called method

What else do we know? Well, it's really

OneConcreteClass(OneClass(anotherVariable))

or

OneConcreteClass(SomethingElseConfusing)

OneConreteClass is thus a concrete class which takes another object in its __init__ method, specifically something of type OneClass which has been initialised with OneClass(anotherVariable)

For further details see Dive into python or here

Community
  • 1
  • 1
doctorlove
  • 18,872
  • 2
  • 46
  • 62
0

In Python almost everything is Object

so when we create instance to an object we do something like this:

obj = ClassName()  # class itself an object of "Type"

or obj = ClassName(Args) # Here args are passed to the constructor

if your class has any member called method()

you can do like as follows:

obj.method()

or

ClassName().method()
Siva Cn
  • 929
  • 4
  • 10