Python Forum
Why does Function behave differently in a class vs. outside a class?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why does Function behave differently in a class vs. outside a class?
#1
# Why does this function behave differently in a class vs. outside a class?
class Test():
    def add_person(element, lineage=[]):
        lineage.append(element)  # AttributeError:  'str' object has no attribute 'append'
        return lineage
z = Test()
g = z.add_person("Test1")
h = z.add_person("Test2")
t = z.add_person("Test3")
print(g, h, t)
# >>Output:
# AttributeError: 'str' object has no attribute 'append'

def add_person3(element, lineage=[]):
    lineage.append(element)
    return lineage

d = add_person3("1")
e = add_person3("2")
f = add_person3("3")
print(d, e, f)

# >>Output:
# # >>Output: 
# ['1', '2', '3'] ['1', '2', '3'] ['1', '2', '3']
Reply
#2
first of all your class is wrong. in order to work (although not as you would expect) it should be like this

 
class Test():
    @staticmethod
    def add_person(element, lineage=[]):
        lineage.append(element)  # AttributeError:  'str' object has no attribute 'append'
        return lineage
z = Test()
g = z.add_person("Test1")
h = z.add_person("Test2")
t = z.add_person("Test3")
print(g, h, t)
you should understand the difference between instance and class methods and properties, which is advanced OOP topic
https://docs.python.org/3/tutorial/class...at-classes
https://stackoverflow.com/a/7554899/4046632
https://stackoverflow.com/a/12179752/4046632

As to the result that differ from what you expect see
http://docs.python-guide.org/en/latest/writing/gotchas/
Reply
#3
Change the method like this:

class Test():
    @staticmethod
    def add_person(element, lineage=[]):
        lineage.append(element)  # AttributeError:  'str' object has no attribute 'append'
        return lineage
[code] [/code]
 
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
Just to add, that you need to start with class basics before you start with more advanced topics. it looks like you are still not comfortable with the basics of OOP
Reply
#5
Another pitfall is the default argument: lineage=[]
If you use this in a function definition, it's evaluated and the object is added to the function.

Lists are mutable objects. If you don't use an argument for lineage, lineage.append(element) appends to the list,
which is inside the function. This means that all future calls do have the same list object, if you don't supply
the lineage keyword with your own new list.

You can prevent this:

def wrong_way(n, some_list=[]):
    some_list.append(n)
    return some_list

def right_way(n, some_list=None):
    if not some_list:
        some_list = [] # this here creates every time a new list, if called without some_list
    some_list.append(n)
    return some_list
To test what happens, do following:

wrong_way(1)
wrong_way(2)
wrong_way(3)
Look what happens with the output.

Repeat this, with the second function:

right_way(1)
right_way(2)
right_way(3)
This version does not return the past elements which were added before.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How does this code create a class? Pedroski55 6 385 Apr-21-2024, 06:15 AM
Last Post: Gribouillis
  class definition and problem with a method HerrAyas 2 257 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  Printing out incidence values for Class Object SquderDragon 3 296 Apr-01-2024, 07:52 AM
Last Post: SquderDragon
  class and runtime akbarza 4 369 Mar-16-2024, 01:32 PM
Last Post: deanhystad
  Operation result class SirDonkey 6 536 Feb-25-2024, 10:53 AM
Last Post: Gribouillis
  The function of double underscore back and front in a class function name? Pedroski55 9 670 Feb-19-2024, 03:51 PM
Last Post: deanhystad
  super() and order of running method in class inheritance akbarza 7 740 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  Class test : good way to split methods into several files paul18fr 4 485 Jan-30-2024, 11:46 AM
Last Post: Pedroski55
  Good class design - with a Snake game as an example bear 1 1,841 Jan-24-2024, 08:36 AM
Last Post: annakenna
  question about __repr__ in a class akbarza 4 615 Jan-12-2024, 11:22 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020