Dote operation help


#1



https://www.codecademy.com/en/courses/python-intermediate-en-WL8e4/2/3?curriculum_id=4f89dab3d788890003000096

Hi, a question to the example in 13.Override. In the example, an variable 'other.name' is used. We did not define an attribute "name" for "other" nor did we apple value to "other.name", how can we use 'other.name' and how python knows "other.name"=other?


class Employee(object):
    def __init__(self, name):
        self.name = name
    def greet(self, other):
        print "Hello, %s" % other.name

ceo = CEO("Emily")
emp = Employee("Steve")
emp.greet(ceo)
# Hello, Emily


#2

Oh, I seems to understand why. Because an object "ceo" is passed to other, other then has the attribute of 'name'. A following up question, can I do the following? which way is better?

class Employee(object):
def init(self, name):
self.name = name
def greet(self, other):
print "Hello, %s" % other

ceo = CEO("Emily")
emp = Employee("Steve")
emp.greet('Emily')


#3

@zhoumax: Whenever we are woking with O.O.P. in Python and we have self.name_attribute_here we are accessing a attribute that's in our class, lets not considere inheritance for now.

Q: But there are two "name"s ?
A: One is your attribute which you're setting a value to it, self.name, and the other one is an argument.

Q: Can two different objects access the same attribute with the same value?
A: In fact you can, as long as you declare outside of any given method. It would be considered "global" within your class so all objects can access and get the same value but that can be dangerous so you better watch out!

Isn't really a matter of which way is better is more like telling which one will "stick together" to your class.

The first code you've posted will print out the name Emily, since this was the value passed to the init function when you instanciated and initialized your object ceo.
Since you're passing that exact same object to the function greet and inside of it you're telling to other, which is a reference to your object ceo, to access the attribute name, it will print out the name who's vinculated with the object.

The second code you've posted can actually work the way it is, since the function greet will know an object of the class Employee is trying to access a method and passing an argument to it, which is Emily, to be printed.

Q: Which one should I choose?
A: The one that follow the instructions that were given to you in that lesson.