0

Add Attribute

How can I add an attribute to a function I'm making in a module?

19th Apr 2020, 7:31 PM
Ahmad Tarek
Ahmad Tarek - avatar
11 ответов
+ 1
Okay thank you. Well its looking like youre treating "perm" as an attribute when it is a function within a function. The way you have it set up, you might as well take off that extra function on the outside, from what youve shown it doesnt really do much. Try deleting that and just trying: print(jkhk.perm('sdfew'))
19th Apr 2020, 8:21 PM
Slick
Slick - avatar
+ 4
In Python every function is also an object. so you can add attributes to function names with the dot notation, for example this is possible: def multiply(number): return number * multiply.factor multiply.factor = 7 print(multiply(3)) # 21 But I don't really see the point of doing this, you should rather use another parameter, or a local variable, or embed your function inside a class like in Slick's example.
19th Apr 2020, 7:51 PM
Tibor Santa
Tibor Santa - avatar
+ 3
Attributes are meant for classes. class Airplane: def __init__(self, name): self.name = name self.wings = 2 self.condition = 'good' p1 = Airplane('Black Hawk') #name, wings, and condition are #attributes of the Airplane object.
19th Apr 2020, 7:46 PM
Slick
Slick - avatar
+ 2
Oh yeah you can!
19th Apr 2020, 7:59 PM
Slick
Slick - avatar
+ 2
You could use Tibor's example up top. Theres nothing wrong with it, just as he said, a bit unnecessary. Youre better off writing functions outside other functions and incorporating them in those functions. def add(a,b): return a + b def addtwice(a,b): return add(a,b)*2
19th Apr 2020, 8:37 PM
Slick
Slick - avatar
+ 1
Tibor Santa Can I put functions into other functions?
19th Apr 2020, 7:57 PM
Ahmad Tarek
Ahmad Tarek - avatar
+ 1
What is jkhk?
19th Apr 2020, 8:08 PM
Slick
Slick - avatar
0
def removedup(iterable): def perm(iterable): if type(iterable) == str: new = "" for i in iterable: c = iterable.count(i) if c < 2: new = new + i if i == " ": new = new + i return new when I type print(jkhk.removedup.perm("sdfew")) It doesn't work
19th Apr 2020, 8:03 PM
Ahmad Tarek
Ahmad Tarek - avatar
0
Slick The module's name(that I made)
19th Apr 2020, 8:13 PM
Ahmad Tarek
Ahmad Tarek - avatar
0
Just ran it, it doesnt give an error, but it doent print anything either. What did you want it to do?
19th Apr 2020, 8:24 PM
Slick
Slick - avatar
0
I would like to put an option to the function removedup as an attribute. But I should learn classes first. Isn't that right
19th Apr 2020, 8:27 PM
Ahmad Tarek
Ahmad Tarek - avatar