Found 10423 Articles for Python

How to declare an attribute in Python without a value?

Vikram Chiluka
Updated on 22-Sep-2022 08:53:00

5K+ Views

In this article, we will show you how to declare an attribute in python without a value. In Python, as well as in several other languages, there is a value that means "no value". In Python, that value with no value is None, let us see how it is used. You simply cannot. Variables are just names in Python. A name always refers to an object ("is bound"). It is conventional to set names that do not yet have a meaningful value but should be present to None. Method 1: By Initializing them with None Directly We can directly assign ... Read More

How to define attributes of a class in Python?

Rajendra Dharmkar
Updated on 20-Feb-2020 10:17:04

296 Views

Attributes of a classEverything, almost everything in Python is an object. Every object has attributes and methods. Thus attributes are very fundamental in Python. A class is a construct which is a collection of similar objects. A class also has attributes. There will be a difference between the class attributes and instance attributes. The class attributes are shared by the instances of the class but it not true vice versa.ExampleWe can get a list of the attributes of an object using the built-in “dir” function. For example −>>> s = 'abc' >>> len(dir(s)) 71 >>> dir(s)[:5] ['__add__', '__class__', '__contains__', '__delattr__', ... Read More

What is difference between self and __init__ methods in python Class?

Rajendra Dharmkar
Updated on 13-Jun-2020 08:30:30

8K+ Views

selfThe word 'self' is used to represent the instance of a class. By using the "self" keyword we access the attributes and methods of the class in python.__init__ method"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.ExampleFind out the cost of a rectangular field with breadth(b=120), length(l=160). It costs x (2000) rupees per 1 square unitclass Rectangle:    def __init__(self, length, breadth, unit_cost=0):        self.length ... Read More

How to create instance Objects using __init__ in Python?

Rajendra Dharmkar
Updated on 13-Jun-2020 08:29:40

845 Views

The instantiation or calling-a-class-object operation creates an empty object. Many classes like to create objects with instances with a specific initial state. Therefore a class may define a special method named __init__(), as follows −def __init__(self) −    self.data = [ ]When a class defines an __init__() method, class instantiation automatically invokes the newly-created class instance which is obtained by −x = MyClass()The __init__() method may have arguments. In such a case, arguments given to the class instantiation operator are passed on to __init__(). For example, >>> class Complex: ...     def __init__(self, realpart, imagpart): ...       ... Read More

How to create class objects in Python?

Rajendra Dharmkar
Updated on 18-May-2023 17:41:16

2K+ Views

In Python, classes are like blueprints for creating objects. Once you define a class, you can create objects (also called instances) based on that class. Here are four ways to create class objects in Python: Creating a Class and an Instance Example In this example, we define a class called `MyClass` using the `class` keyword. We then create an instance of the class called `obj` using parentheses `()` after the class name. This creates an empty object that is an instance of the class. class MyClass: pass obj = MyClass() print(obj) Output ... Read More

How do I sort a list of dictionaries by values of the dictionary in Python?

Malhar Lathkar
Updated on 31-Jan-2023 18:05:35

661 Views

In this article, we will show how to sort a list of dictionaries by the values of the dictionary in Python. Sorting has always been a useful technique in everyday programming. Python's dictionary is often used in a wide range of applications, from competitive to developer-oriented (example-handling JSON data). It can be useful in certain situations to be able to filter dictionaries based on their values. Below are the 2 methods to accomplish this task − Using sorted() and itemgetter Using sorted() and lambda functions What is a Dictionary? Dictionaries are Python's version of an associative array data ... Read More

How can I get last 4 characters of a string in Python?

Malhar Lathkar
Updated on 20-Feb-2020 08:12:13

2K+ Views

The slice operator in Python takes two operands. First operand is the beginning of slice. The index is counted from left by default. A negative operand starts counting from end. Second operand is the index of last character in slice. If omitted, slice goes upto end.We want last four characters. Hence we count beginning of position from end by -4 and if we omit second operand, it will go to end.>>> string = "Thanks. I am fine" >>> string[-4:] 'fine'

How to write a Python regular expression to match multiple words anywhere?

Rajendra Dharmkar
Updated on 20-Feb-2020 05:31:13

3K+ Views

The following code using Python regex matches the given multiple words in the given stringExampleimport re s = "These are roses and lilies and orchids, but not marigolds or .." r = re.compile(r'\broses\b | \bmarigolds\b | \borchids\b', flags=re.I | re.X) print r.findall(s)OutputThis gives the output['roses', 'orchids', 'marigolds']

How do you validate a URL with a regular expression in Python?

Rajendra Dharmkar
Updated on 13-Jun-2020 07:28:42

592 Views

There's no validate method as almost anything is a valid URL. There are some punctuation rules for splitting it up. Without any punctuation, you still have a valid URL.Depending on the situation, we use following methods.If you trust the data, and just want to verify if the protocol is HTTP, then urlparse is perfect.If you want to make the URL is actually a true URL, use the cumbersome and maniacal regexIf you want to make sure it's a real web address, use the following codeExampleimport urllib try:     urllib.urlopen(url) except IOError:     print "Not a real URL"Read More

How to read and write unicode (UTF-8) files in Python?

Rajendra Dharmkar
Updated on 20-Feb-2020 07:59:19

28K+ Views

The io module is now recommended and is compatible with Python 3's open syntax: The following code is used to read and write to unicode(UTF-8) files in PythonExampleimport io with io.open(filename,'r',encoding='utf8') as f:     text = f.read() # process Unicode text with io.open(filename,'w',encoding='utf8') as f:     f.write(text)

Advertisements