python append function as dot notation

  • Last Update :
  • Techknowledgy :

If func is an actual function of obj you can simply call it:

func()

An example:

class Klass(object):
   def say_hi(self):
   print 'hi from', self

func = Klass().say_hi
func() # hi from < __main__.Klass object at 0x024B4D70 >

Otherwise if func is the name of the function (a string) then this will get it and call it:

getattr(obj, func)()

First I have defined a simple class then I have tried to access its instance method according to this question.

>>> # Defining class
...
>>>
class MyClass(object):
   ...def __init__(self):
   ...self.name = "Rishikesh Agrawani"
   ...self.age = 25
   ...def doStuff(self):
   ...print "DETAILS:\n"
   ...print "NAME: %s" % (self.name)
   ...print "AGE : %d" % (self.age)
   ...
   >>>
   # Instantiation
   ...
   >>>
   obj = MyClass() >>>
   func = getattr(obj, "doStuff"); >>>
func()
DETAILS:

   NAME: Rishikesh Agrawani
AGE: 25 >>>

Finally

>>> def do_something(obj, func):
... obj.func()
...
>>> do_something(obj, func)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in do_something
         AttributeError: 'MyClass' object has no attribute 'func'
         >>>
         >>> def do_something(obj, func):
         ... print obj, func
         ...
         >>> do_something(obj, func)
         <__main__.MyClass object at 0x100686450>
            <bound method MyClass.doStuff of <__main__.MyClass object at 0x100686450>>
               >>>
               >>>
               >>> def do_something(obj, func):
               ... func()
               ...
               >>> do_something(obj, func)
               DETAILS:

               NAME: Rishikesh Agrawani
               AGE : 25
               >>>

Suggestion : 2

Last Updated : 10 May, 2020

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

So overall complexity to append n elements is

1 + .....(n - 2) times...+1 = O(n)

Suggestion : 3

Python has a built-in type conversion function called list that tries to turn whatever you give it into a list.,We have already seen that we can assign list values to variables or pass lists as parameters to functions:,If a function modifies the items of a list parameter, the caller sees the change.,Although a list can contain another list, the nested list still counts as a single element in its parent list. The length of this list is 4:

1
2
ps = [10, 20, 30, 40]
qs = ["spam", "bungee", "swallow"]
1
zs = ["hello", 2.0, 5, [10, 20]]
1
2
3
4
5
>>> vocabulary = ["apple", "cheese", "dog"] >>>
   numbers = [17, 123] >>>
   an_empty_list = [] >>>
   print(vocabulary, numbers, an_empty_list)["apple", "cheese", "dog"][17, 123][]