{"id":8273,"date":"2023-11-09T18:43:28","date_gmt":"2023-11-09T13:13:28","guid":{"rendered":"https:\/\/python-programs.com\/?p=8273"},"modified":"2023-11-10T12:24:11","modified_gmt":"2023-11-10T06:54:11","slug":"python-data-persistence-constructor","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-data-persistence-constructor\/","title":{"rendered":"Python Data Persistence – Constructor"},"content":{"rendered":"

Python Data Persistence – Constructor<\/h2>\n

We provide a constructor method to our class to initialize its object. The__init__( ) method defined inside the class works as a constructor. It makes a reference to the object as the first positional argument in the form of a special variable called \u2018self\u2019. Java\/C++ programmers will immediately relate this to \u2018this\u2019 variable. A method with \u2018self argument is known as an instance method. Save the following script as myclass.py. It provides two instance variables (my name and my age) and about () method.<\/p>\n

Example<\/strong><\/p>\n

#myclass.py \u2018\r\nclass MyClass:\r\n            def __init__(self):\r\nself.myname='Ashok'\r\nself.myage=21\r\ndef about(self):\r\nprint ('My name is { } and I am { } years old'.format(self.myname,self.myage))<\/pre>\n

Let us use this script as a module, import MyClass from it and have its object.<\/p>\n

Example<\/strong><\/p>\n

>>> from myclass import MyClass\r\n>>> obj1=MyClass( )\r\n> > > obj1.myname\r\n'Ashok'\r\n>>> obj1.myage\r\n21\r\n>>> obj1.about()\r\nMy name is Ashok and I am 21 years old<\/pre>\n

So, now each object will have the same attributes and methods as defined in the class. However, attributes of each object will be initialized with the same values as assigned in__init__( ) method. To counter this, we can have a parameterized constructor, optionally with default values. Modify Now we can have objects having attributes with different values.<\/p>\n

Example<\/strong><\/p>\n

>>> from myclass import MyClass\r\n>>> obj1=MyClass('Ashok', 21)\r\n>>> obj2=MyClass('Asmita',20)\r\n>>> obj1.about()\r\nMy name is Ashok and I am 21 years old\r\n>>> obj2.about()\r\nMy name is Asmita and I am 20 years old<\/pre>\n

However, does this process prevent the dynamic addition of an attribute to an object\/class? Well, not really.<\/p>\n

>>> setattr(obj1marks50)\r\n>>> obj1.marks\r\n50\r\n\r\n<\/pre>\n

So, how do we ensure that the object will have only those attributes as per the class definition? The answer is slots .<\/p>\n

_slots_<\/strong><\/p>\n

To prevent any further attribute to be added to an object of a class, it carries a variable named as__slots__<\/strong>. This variable is defined before__init__ () method. It is a list of allowed attributes to be initialized by the constructor. The setattr () function will first check if the second argument is in the__slots__<\/strong>list and assign it a new value only if it exists.<\/p>\n

Example<\/strong><\/p>\n

#myclass.py\r\nclass MyClass:\r\n          __slots___=['myname', 'myage']\r\n         def__init___(self, name=None, age=None):\r\n                 self.myname=name\r\n                 self.myage=age\r\ndef about(self):\r\n               print ('My name is { } and I am { } years old1.format(self.myname,self.myage))<\/pre>\n

Import the modified class and check the effect of__slots___variable.<\/p>\n

Example<\/strong><\/p>\n

>>> from myclass import MyClass\r\n>>> obj1=MyClass('Ashok', 21)\r\n> > > obj1.about( )\r\nMy name is Ashok and I am 21 years old\r\n>>> setattr(obj1, 'marks', 50) #new attribute not allowed\r\nTraceback (most recent call last):\r\nFile \"<stdin>\", line 1, in <module>\r\nAttributeError: 'MyClass' object has no attribute 'marks'\r\n>>> setattr(obj1, 'myage', 25) #value of existing module can be modified\r\n>>> obj1.about()\r\nMy name is Ashok and I am 25 years old<\/pre>\n

 <\/p>\n","protected":false},"excerpt":{"rendered":"

Python Data Persistence – Constructor We provide a constructor method to our class to initialize its object. The__init__( ) method defined inside the class works as a constructor. It makes a reference to the object as the first positional argument in the form of a special variable called \u2018self\u2019. Java\/C++ programmers will immediately relate this …<\/p>\n

Python Data Persistence – Constructor<\/span> Read More »<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[5],"tags":[],"yoast_head":"\nPython Data Persistence - Constructor - Python Programs<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/python-programs.com\/python-data-persistence-constructor\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Data Persistence - Constructor - Python Programs\" \/>\n<meta property=\"og:description\" content=\"Python Data Persistence – Constructor We provide a constructor method to our class to initialize its object. The__init__( ) method defined inside the class works as a constructor. It makes a reference to the object as the first positional argument in the form of a special variable called \u2018self\u2019. Java\/C++ programmers will immediately relate this … Python Data Persistence – Constructor Read More »\" \/>\n<meta property=\"og:url\" content=\"https:\/\/python-programs.com\/python-data-persistence-constructor\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Programs\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/btechgeeks\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-09T13:13:28+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-10T06:54:11+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@btech_geeks\" \/>\n<meta name=\"twitter:site\" content=\"@btech_geeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prasanna\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Organization\",\"@id\":\"https:\/\/python-programs.com\/#organization\",\"name\":\"BTech Geeks\",\"url\":\"https:\/\/python-programs.com\/\",\"sameAs\":[\"https:\/\/www.instagram.com\/btechgeeks\/\",\"https:\/\/www.linkedin.com\/in\/btechgeeks\",\"https:\/\/in.pinterest.com\/btechgeek\/\",\"https:\/\/www.youtube.com\/channel\/UC9MlCqdJ3lKqz2p5114SDIg\",\"https:\/\/www.facebook.com\/btechgeeks\",\"https:\/\/twitter.com\/btech_geeks\"],\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png\",\"contentUrl\":\"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png\",\"width\":350,\"height\":70,\"caption\":\"BTech Geeks\"},\"image\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/logo\/image\/\"}},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/python-programs.com\/#website\",\"url\":\"https:\/\/python-programs.com\/\",\"name\":\"Python Programs\",\"description\":\"Python Programs with Examples, How To Guides on Python\",\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/python-programs.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-constructor\/#webpage\",\"url\":\"https:\/\/python-programs.com\/python-data-persistence-constructor\/\",\"name\":\"Python Data Persistence - Constructor - Python Programs\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/#website\"},\"datePublished\":\"2023-11-09T13:13:28+00:00\",\"dateModified\":\"2023-11-10T06:54:11+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-constructor\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/python-programs.com\/python-data-persistence-constructor\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-constructor\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/python-programs.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python Data Persistence – Constructor\"}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-constructor\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-constructor\/#webpage\"},\"author\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb\"},\"headline\":\"Python Data Persistence – Constructor\",\"datePublished\":\"2023-11-09T13:13:28+00:00\",\"dateModified\":\"2023-11-10T06:54:11+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-constructor\/#webpage\"},\"wordCount\":292,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/python-programs.com\/python-data-persistence-constructor\/#respond\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb\",\"name\":\"Prasanna\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g\",\"caption\":\"Prasanna\"},\"url\":\"https:\/\/python-programs.com\/author\/prasanna\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Data Persistence - Constructor - Python Programs","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/python-programs.com\/python-data-persistence-constructor\/","og_locale":"en_US","og_type":"article","og_title":"Python Data Persistence - Constructor - Python Programs","og_description":"Python Data Persistence – Constructor We provide a constructor method to our class to initialize its object. The__init__( ) method defined inside the class works as a constructor. It makes a reference to the object as the first positional argument in the form of a special variable called \u2018self\u2019. Java\/C++ programmers will immediately relate this … Python Data Persistence – Constructor Read More »","og_url":"https:\/\/python-programs.com\/python-data-persistence-constructor\/","og_site_name":"Python Programs","article_publisher":"https:\/\/www.facebook.com\/btechgeeks","article_published_time":"2023-11-09T13:13:28+00:00","article_modified_time":"2023-11-10T06:54:11+00:00","twitter_card":"summary_large_image","twitter_creator":"@btech_geeks","twitter_site":"@btech_geeks","twitter_misc":{"Written by":"Prasanna","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Organization","@id":"https:\/\/python-programs.com\/#organization","name":"BTech Geeks","url":"https:\/\/python-programs.com\/","sameAs":["https:\/\/www.instagram.com\/btechgeeks\/","https:\/\/www.linkedin.com\/in\/btechgeeks","https:\/\/in.pinterest.com\/btechgeek\/","https:\/\/www.youtube.com\/channel\/UC9MlCqdJ3lKqz2p5114SDIg","https:\/\/www.facebook.com\/btechgeeks","https:\/\/twitter.com\/btech_geeks"],"logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/logo\/image\/","url":"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png","contentUrl":"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png","width":350,"height":70,"caption":"BTech Geeks"},"image":{"@id":"https:\/\/python-programs.com\/#\/schema\/logo\/image\/"}},{"@type":"WebSite","@id":"https:\/\/python-programs.com\/#website","url":"https:\/\/python-programs.com\/","name":"Python Programs","description":"Python Programs with Examples, How To Guides on Python","publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/python-programs.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/python-programs.com\/python-data-persistence-constructor\/#webpage","url":"https:\/\/python-programs.com\/python-data-persistence-constructor\/","name":"Python Data Persistence - Constructor - Python Programs","isPartOf":{"@id":"https:\/\/python-programs.com\/#website"},"datePublished":"2023-11-09T13:13:28+00:00","dateModified":"2023-11-10T06:54:11+00:00","breadcrumb":{"@id":"https:\/\/python-programs.com\/python-data-persistence-constructor\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/python-programs.com\/python-data-persistence-constructor\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/python-programs.com\/python-data-persistence-constructor\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/python-programs.com\/"},{"@type":"ListItem","position":2,"name":"Python Data Persistence – Constructor"}]},{"@type":"Article","@id":"https:\/\/python-programs.com\/python-data-persistence-constructor\/#article","isPartOf":{"@id":"https:\/\/python-programs.com\/python-data-persistence-constructor\/#webpage"},"author":{"@id":"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb"},"headline":"Python Data Persistence – Constructor","datePublished":"2023-11-09T13:13:28+00:00","dateModified":"2023-11-10T06:54:11+00:00","mainEntityOfPage":{"@id":"https:\/\/python-programs.com\/python-data-persistence-constructor\/#webpage"},"wordCount":292,"commentCount":0,"publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/python-programs.com\/python-data-persistence-constructor\/#respond"]}]},{"@type":"Person","@id":"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb","name":"Prasanna","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g","caption":"Prasanna"},"url":"https:\/\/python-programs.com\/author\/prasanna\/"}]}},"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8273"}],"collection":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/comments?post=8273"}],"version-history":[{"count":2,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8273\/revisions"}],"predecessor-version":[{"id":9420,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8273\/revisions\/9420"}],"wp:attachment":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/media?parent=8273"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/categories?post=8273"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/tags?post=8273"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}