oop - Do the attributes in python classes change value if given the same name? -
i learning python oop programming , running little script:
class employee: def __init__(self, first, last): self.first = first self.last = last emp1 = employee("fede", "cuci") print emp1.first print emp1.last everything worked fine, until noticed when created method same attributes, , printed them out, take values instead:
class employee: def __init__(self, first, last): self.first = first self.last = last def fullname(self, first, last): self.first = first self.last = last def other_fullname(self, first, last): self.first = first self.last = last emp1 = employee("fede", "cuci") emp1.fullname("fede2", "cuci2") emp1.other_fullname("fede3", "cuci3") print emp1.first print emp1.last and noticed print out last method called. mean should name attributes differently in each class , use technique update attribute's value, or have done wrong in code?
i thought putting "self" in each method, make attribute unique specific method, not if tried print out attribute again, update it's value based on method called last...
please correct me if wrong, in advance,
fede
self reference current instance. attributes on instance not unique each method, no. whole point of methods able manipulate state of instance.
print 2 attributes after each method call, , you'll see change each method manipulating attributes:
>>> emp1 = employee("fede", "cuci") >>> emp1.first 'fede' >>> emp1.last 'cuci' >>> emp1.fullname("fede2", "cuci2") >>> emp1.first 'fede2' >>> emp1.last 'cuci2' >>> emp1.other_fullname("fede3", "cuci3") >>> emp1.first 'fede3' >>> emp1.last 'cuci3' so yes, if each method needs have own state tied instance, you'll need use unique names.
if attributes unique each method, never have 2 different methods operate on same piece of information.
Comments
Post a Comment