Kristof Pal
Kristof Pal

Reputation: 1026

Do not understand this line of code in Python?

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

Upvotes: 0

Views: 180

Answers (4)

Aleph
Aleph

Reputation: 1219

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()

Upvotes: 4

Josha Inglis
Josha Inglis

Reputation: 1048

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.

Upvotes: 1

Siva Cn
Siva Cn

Reputation: 947

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()

Upvotes: 0

doctorlove
doctorlove

Reputation: 19232

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

Upvotes: 0

Related Questions