This question already has an answer here:
python string module vs str methods
(1 answer)
Closed 6 years ago.
I am new to programming therefore may sound idiotic. I am learning python where I am not able to understand how few methods like upper(), split() etc work.
I mean you directly use like below:
"ABC".upper() or "abc,xyz".split(",")
Or, you can first import string and then call these methods like below:
import string
string.upper("abc")
string.split("abc,xyz", ",")
What is the difference, and how would we import string module when we can achieve the same output without importing it.
Are there similar cases exist apart from string module?
In fact, one of the paradigm you can use in Python is the Object Oriented Programming, where you modify object state through "methods" like this: myobject.mymethod().
Syntactically, it means that the first argument of the method mymethod() is in fact the object itself. But, as Python want also to deal with other paradigms (functional programming, imperative programming, and so on), there is two syntactical ways to address this method.
One is simply as I mentioned before: myobject.mymethod(), and the other one is simply to consider that the first argument is the object itself: mymethod(myobject).
More precisely, you can realize that when you define by yourself a method because you have to specify the first argument by self which is a reference to the object itself like this:
def mymethod(self):
pass
Related
This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 8 months ago.
How else can I implement a function without using ' '.join(str, name). I use this to convert tuple to str. And function def get_text should look:
def get_text(name):
return "Hello " + name
Is there another way to implement that?
def bold(get_text):
def wrapped(*name):
return "<b>{}</b>".format(get_text(" ".join(map(str, name))))
return wrapped
def italic(get_text):
def wrapped(name):
return "<i>{}</i>".format(get_text(name))
return wrapped
def underline(get_text):
def wrapped(name):
return "<u>{}</u>".format(get_text(name))
return wrapped
#bold
#italic
#underline
def get_text(*name):
return "hello " + " ".join(map(str, name))
print(get_text('Hi', 'world'))
Function returns:
<b><i><u>hello Hi world</u></i></b>
First of all, you try to re-invent wheel. If you want to make html/xml etc. page from python - there are already libraries/frameworks and tutorials for this, that will suit you much better.
However, if it's just he beginning of your programming journey, string manipulation is one of first steps.... however you also have tons of tutorials for this. Python has multiple methods to format strings (best depends on usage, really)... e.g.
fstrings (https://realpython.com/python-f-strings/)
string format (https://www.w3schools.com/python/ref_string_format.asp)
strings concatenation (but you want to avoid that one)
Basically, string documentation is where you want to look (also, tutorials above will do the trick as well)
What you are attempting to use here is using decorators - you've possibly looked to tutorial about decorators instead strings (this is quite nice and easy example to learn decorators, but decorators itself are quite complex for starters and can be confusing...)
For basic idea, decorators are methods, that wraps around another methods... let's say, you want to log time before method and after it. You could do that in that methods body, but your method should only be focused on doing one thing. E.g. method add should only add not, measure time, add, then measure time. Also, this binds measuring to your method - therefore you cannot use your method without measurement. Doesn't sound too flexible, and starts to be bit messy too...
So decorator is a nice way to have your 'inner' method body clean and focused on its role, but extending it with another functionality... Wrapping method and inner method are also independent (most of cases), and can be quickly separated... Also imagine, that you want to measure time of 'a lot of' your methods, but not every - so you put that decorator only with those methods, you want.
This question already has answers here:
Dictionary vs Object - which is more efficient and why?
(8 answers)
Closed 9 years ago.
Refer to the following code as an example:
import numpy as np
N = 200
some_prop = np.random.randint(0,100, [N, N, N])
#option 1
class ObjectThing():
def __init__(self, some_prop):
self.some_prop = some_prop
object_thing = ObjectThing(some_prop)
#option 2
pseudo_thing = {'some_prop' : some_prop }
I like the structure that option 1 provides, it makes the operation of an application more rigid and whatnot. However, I'm wondering if there are other more absolute benefits that I'm not aware of.
The obvious advantage of using objects is that you can extend their functionality beyond simply storing data. You could, for instance, have two attributes, and define and __eq__ method that uses both attributes in some way other than simply comparing both of them and returning False unless both match.
Also, once you've got a class defined, you can easily define new instances of that class that will share the structure of the original, but with a dictionary, you'd either have to redefine that structure or make a copy of some sort of the original and then change each element to match the values you want the new pseudo-object to have.
The primary advantages of dictionaries are that they come with a variety of pre-defined methods (such as .items()), can easily be iterated over using in, can be conveniently created using a dict comprehension, and allow for easy access of data "members" using a string variable (though really, the getattr function achieves the same thing with objects).
If you're using an implementation of Python that includes a JIT compiler (e.g. PyPy), using actual objects can improve the compiler's ability to optimize your code (because it's easier for the compiler to reason about how members of an object are utilized, unlike a plain dictionary).
Using objects also allows for subclassing, which can save some redundant implementation.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
python 'self' explained
I am a beginner in Python. I was going through the tutorials on Classes and Iterators when I had a doubt that I was unable to explain to myself. The program text below was a part of a class which calculates area.
def __init__(self,len,wid):
self.length=len
self.width=wid
def calculate_area(self)
return self.length*self.width
def print_area(self)
print 'Area='+str(self.calculate_area())
What I am unable to understand is why do the function's argument list have "self"? What is its role? Why are every variable resolved with "self"?
This is similar to this pointer in C++ (if you have come from C++ background)
Typical usage would be that the members of objects can be referenced by self in case if there is an ambiguity. e.g.
def calculate_area(self, length)
return self.length*self.width
Above length is an argument for calculate_area function.
if the object also has length member then it can be resolved by using self.length
Refer existing answer here:
What is the purpose of self?
I really don't know I'm too new on the Python world but I think that Python does not provide the this value as C# or Java do, so this is the mechanism that Python use to define itself in its classes.
Anyway you can see that you don't need to pass the self as parameter in the function call, because Python does for you.
This is my theory, but I'm also interested to know it so If anyone can say more about this, I think we will be very thankfull.
See you!
I am going over a Python tutorial the one where the following example is demonstrated:
>>> 'str'.strip() + 'ing' # <- This is ok
In this example (as i understand it) str is a string, on which function strip() is called.
I would reasonably expect to find that function doing >>> dir("abc"). Indeed function is listed as 'strip'
Question 1: Why are some functions listed as __name__ and others as name?
Question 2: I would like now to find more information about this function. When running help("abc") (expecting to get a man page on all functions that can be ran on string), strip is not listed. Why? Where can i find out more about particular function?
Question 3: Using PyCharm i would expect the following autocompletion to work and yet, i see nothing. Why is that?
Functions surrounded by double underscores are special functions that can be overridden to implement special behaviors. For example, the __getitem__ function, when implemented in a class, allows indexed access to items in that class. (In other words, a[5] is equivalent in most contexts to a.__getitem__(5)). The underscores just signal that they're special, and require some special handling. (For example, don't invent your own.)
When you pass a string to help, it treats the string as a query. For example, help('class') brings up a bunch of information about classes. If you want the help text for string objects, do help(str) or help('str').
I don't use PyCharm, so I can't help there.
Instead of help("abc") which gives help on abstract base classes, try help(str) which gives help on strings, including the str.strip method.
Answer for 3. Make sure you have Python Interpreter specified in Settings | Project Interpreter?
Here is what I get for your example:
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
python ‘self’ explained
Why do you need explicitly have the “self” argument into a Python method?
Why does Python require the "self" parameter for methods?
For example def method_abc(self, arg1)
And is there ever a date that the need for it will be removed?
Python gives you the option of naming it something other than self, even though the standard is to name it self. Just as it gives you the option of using tabs for indents, even though the standard is to use spaces.
In other words, it's not just "assumed" because...
To give you naming flexibility
To make it clearer that something will be passed self (or not).