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
  Python inner classes inheritance from parent class Abedin 8 782 Apr-23-2025, 05:56 AM
Last Post: Gribouillis
  Accessing method attributes of python class Abedin 6 931 Apr-14-2025, 07:02 AM
Last Post: buran
  Python class members based on a type value voidtrance 7 1,292 Apr-11-2025, 10:10 PM
Last Post: deanhystad
  Create a new subclass in a Python extension based on an existing class voidtrance 6 1,453 Mar-25-2025, 06:37 PM
Last Post: voidtrance
  Endgame engine with non-standard figures doesn't behave correctly max248 0 494 Dec-07-2024, 12:44 PM
Last Post: max248
  printing/out put issue with class arabuamir 3 1,019 Aug-25-2024, 09:29 AM
Last Post: arabuamir
  Class test : good way to split methods into several files paul18fr 5 3,862 Jul-17-2024, 11:12 AM
Last Post: felixandrea
  [split] Class and methods ebn852_pan 15 3,435 May-23-2024, 11:57 PM
Last Post: ebn852_pan
  How returns behave in a function with multiple returns? khasbay 1 848 May-19-2024, 08:48 AM
Last Post: deanhystad
  compare parts of a 2-tuple differently Skaperen 0 874 May-18-2024, 08:52 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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