-1

I am trying to understand object oriented programming of python.

In the following code when I omit class Dataset and pass statement from function read_data_set and try to create object without giving some argument - I get error that positional arguments a missing. But when I run this code without omitting anything it works fine even if I don't mention positional arguments while creating object.

Why it doesn't raise error in this case? Can someone please guide me whats going on in the following code?

Secondly I also want to know that when I mention class Dataset with a pass statement does it mean that I am creating a new class or does it mean I am just redefining this?

class Dataset:
    def __init__(self,MC_sample,MC_label):
        self.__MC_sample = MC_sample
        self.__MC_label = MC_label

def read_data_set():
    class Dataset:
        pass
    data_sets = Dataset()  #object created
    return data_sets
user10163680
  • 253
  • 2
  • 11

1 Answers1

0

It's surprising that it works because you must have indentation after the def ... line.

If you have indentation like :

class Dataset:
    def __init__(self,MC_sample,MC_label):
        self.__MC_sample = MC_sample
        self.__MC_label = MC_label

def read_data_set():
    class Dataset:
        pass
    data_sets = Dataset()  #object created
    return data_sets

It works and the class DataSet inside read_data_set shadows the class outside.

If you omit class Dataset: pass, it try to initialize the first DataSet which requires 2 arguments in the constructor (MC_sample and MC_label) so you have an error.

So you can create your class like this :

data_sets = Dataset('MC_sample', 'MC_label')  #object created

Or give default values in the constructor :

def __init__(self,MC_sample='default MC_sample',MC_label='default MC_label'):
    self.__MC_sample = MC_sample
    self.__MC_label = MC_label
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • "class DataSet inside read_data_set shadows the class outside". Can you please explain this line with some example – user10163680 Aug 21 '18 at 11:49
  • shadows the class outside means that the class definition in the local scope of the function has the same name as the class outside of the function. The result is that the original definition is inaccessible inside the function. I am not sure what your purpose with the second class definition is, it looks like a forward declaration from C, which is unnecessary with python, it does not have the same strict typing. See [this link about duck typing](https://stackoverflow.com/questions/4205130/what-is-duck-typing) – vriesdemichael Aug 21 '18 at 12:11