0

To be more clear: Is there any difference between "Goodbye" and "Farewell" in this example? Does one hold any advantages over the other?

class Hello(object):

    def hi(self):
        pass

class Goodbye(object):

    def __init__(self):
        self.hello = Hello()

class Farewell(object):

    hello = Hello()
supernikio2
  • 15
  • 1
  • 5

2 Answers2

0

Yes. The difference between the Goodbye class and the Farewell class is that Goodbye has an instance member hello, while the Farewell class has a class member hello. If you change the Hello class that belongs to a Farewell object, then all instances of Farewell see the change, so you can do this:

a = Goodbye()
b = Goodbye()

a.hello.member = 1 # monkey-patching the member
b.hello.member = 2

print(a.hello.member) # prints "1"
print(b.hello.member) # prints "2"

f = Farewell()
g = Farewell()

f.hello.member = 1
g.hello.member = 2

print(f.hello.member) # prints "2"!

The reason this works is because, as you have defined it, instances of the Goodbye class have their own instance of a Hello object, while all instances of the Farewell class share the same Hello object. Check out the documentation to learn more!

Now whether or not one holds any advantage over the other is implementation-dependent. Class members can sometimes be confusing to users who might expect different instances of a class to retain their own state independent of other actions (i.e., mutable class members can break encapsulation.) However, it might be useful from an efficiency point of view to define members that are constant across all classes (making sure to somehow note this to the users, like hiding them behind underscore prefixes or clear documentation).

PaSTE
  • 4,050
  • 18
  • 26
0

Consider the following example:

class Hello(object):

    def hi(self):
        print("Hello")

class Goodbye(object):

    def __init__(self):
        self.hello = Hello()
        print("this is the Goodbye text")

class Farewell(object):

    hello = Hello()
    print("this is the Farewell text")

__init__ is called when the object of that class is constructed. So you won't see the text "this is the goodbye text" until you create a Goodbye() object (something like s = Goodbye()). However, you will see "this is the Farewell text" when you run your python script containing the Farewell class, but you will NOT see "this is the Farewell text" when you create an object of the Farewell class.

Patrick Conwell
  • 630
  • 1
  • 5
  • 10