2

I am trying to figure the best way to connect classes. Specifically, I want to know whether it is Pythonic to reference an object when creating a class.

So here are two examples that produce the same outcome:

Example 1

class A:
    def __init__(self,content):
        self.content = content

class B:
    def __init__(self):
        self.content = a.content

a = A('test')
b = B()
print(b.content)

Example 2

class A:
    def __init__(self,content):
        self.content = content

class B:
    def __init__(self,other_object):
        self.content = other_object.content

a = A('test')
b = B(a)
print(b.content)

In example 1 the object a is being used inside of the class. In example 2 that object is passed in as argument.

I get that example 2 is the better option because it is more deliberate, but would example 1 still be good practice?

1
  • That depends... do you always only need exactly one instance of A and under the global name a? If not, go for Example2. Commented May 26, 2020 at 10:38

2 Answers 2

1

The two are implementing two fundamentally different functionalities:

  • in the first approach you do not expose the object to work upon and rely on some global name to be defined.
  • in the second you explicitly ask for an object to use, which makes class B more self-contained.

Generally speaking, code that rely on global non-built-in names is considered bad practice.

But there are situations were this is acceptable. For example, if a is holding an expensive computation that you do not really want to recompute each time (and even then, you could use memoization instead), then using a global name may be acceptable, but should be clearly documented.

Sign up to request clarification or add additional context in comments.

Comments

0

The first code is in my mind not good practice. Because a is initialized below the definition of B. So it is very counter intuitive to read.

The best solution depends on what the underlying logic is. Example 1 would be relevant if the class A is a singleton, e.g a database. But the initialization of a should be above B in my opinion.

If you always pass the same instance then it make sense to "hardcode" the attribute in the class otherwise I would use Example 2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.