Is there any difference between these three listings?

  • Thread starter user366312
  • Start date
  • Tags
    Difference
In summary: What is the basic difference between listing1.py and listing3.py? Is there ever a need for listing3.py?There might be a need for listing3.py if you need to store multiple values for an attribute on a class instance. In that case, it would be more convenient to have a single location in which to store the values rather than have them be dynamically allocated each time the set method is called.
  • #1

user366312

Gold Member
89
3
TL;DR Summary
Is there any difference between these three listings?
listing1.py:
    class MyClass:
        def set(self, x, y):
            self.x = x
            self.y = y
    
    obj = MyClass()
    obj.set(10, "Integer")
    
    print(obj.x)
    print(obj.y)

listing2.py:
    class MyClass:
        pass
    
    obj = MyClass()
    obj.x = 10
    obj.y = "Integer"
    
    print(obj.x)
    print(obj.y)

listing3.py:
    class MyClass:
        x = 0;
        y = ""
        def set(self, x, y):
            self.x = x
            self.y = y
    
    obj = MyClass()
    obj.set(10, "Integer")
    
    print(obj.x)
    print(obj.y)
Is there any **practical** difference between these three listings?

What is the **theoretical** difference between these three listings?
 
Technology news on Phys.org
  • #2
What do YOU think and why?
 
  • #3
phinds said:
What do YOU think and why?

1. listing2.py doesn't make any sense to me. Why would someone want to create properties on the fly? Is there really any advantage except creating ambiguity and confusion? Why would a programming language even allow that? Why would a programmer even want to do that?
2. What is the basic difference between listing1.py and listing3.py? Is there ever a need for listing3.py?
 
  • #4
I think # is a matter of style, probably more comfortable for long-time non-OOP programmers.
 
  • #5
user366312 said:
Is there any **practical** difference between these three listings?

Yes. Listings 1 and 2 will throw an AttributeError exception if attributes x or y are accessed on a MyClass instance before the set method is called (in listing 1) or the attributes are set by hand (in listing 2). That's why it's good programming practice to either implement a constructor (an __init__ method) that sets attributes like x and y, or provide class defaults for them as listing 3 does. That way every class instance is guaranteed to have some value for the attribute and not throw an exception when that attribute is accessed.

user366312 said:
What is the **theoretical** difference between these three listings?

What do you mean by "theoretical"?
 
  • Like
Likes sysprog
  • #6
user366312 said:
Why would someone want to create properties on the fly?

For lots of possible reasons which are way too long to fit into a PF post.

In my experience, programming languages fall into two categories: the ones that try to restrict what programmers can do to keep things "safe", and the ones that don't. Python is a language of the second type; the language designers wanted to leave as much leeway to the programmer as possible, because no language designer can possibly foresee all of the things programmers might want to do.
 
  • Like
Likes sysprog
  • #7
Programming languages are usually described in a two-dimensional spectrum: strong\weak and static\dynamic. Though static\dynamic axis is practically binary.

Strong versus Weak is about how much the compiler\interpreter allows you to subvert the type system.

Static versus Dynamic is about when types are checked -- before execution of the program (compile time) or during program execution (runtime).

Examples:
Weak Static: C
Strong Static: C#
Strong Dynamic: Python
Weak Dynamic: Perl

When you choose a dynamic language you are sacrificing some guarantees that your program won't encounter certain classes of errors at runtime for the ability to write code in a less formal and arguably easier way.

Static typing can be thought of as a form of limited program verification. Once you have established certain axioms about your code the compiler can make a lot of optimizations it couldn't have otherwise.
 
  • #8
user366312 said:
1. listing2.py doesn't make any sense to me. Why would someone want to create properties on the fly?
As @PeterDonis indicated, there can be a lot of reasons. Self-modifying code is sometimes useful (but can be treacherous). One extreme example might be in the area of neural networks (NN). Some NNs actually analyze inputs and define classifications and properties for the data. Suppose you had code that was supposed to act on those classifications and properties with no programmer intervention. Then it would be a great advantage for the code to be able to create properties on the fly.
 
  • Like
Likes sysprog
  • #9
All example 2 is doing is creating a new key value pair in an associative array. You'd do it for the same reason you'd dynamically allocate any other key value pair in any other language.
 
  • Like
Likes FactChecker
  • #10
DavidSnider said:
Strong Dynamic: Python

The classification of Python as "Strong" probably merits some clarification, since many programmers will probably feel that being able to instantiate a class and then add attributes to it on the fly counts as "subverting the type system".

I would guess that the reason you are calling Python's typing Strong is that, as far as the interpreter is concerned, you can only create objects of certain types, defined at the C level, and once an object is created its type is fixed forever. There is no way to "cast" an object of one type to another type as there is in C. But as far as the interpreter is concerned, all user-defined classes are one type; subclassing and inheritance at the level of Python code (the "class" statement and all that goes with it) does not change the type of an object at the level of the C code running inside the interpreter. (Strictly speaking, there is more than one type at the C level of the interpreter that a user-defined class at the Python level can inherit from; the usual one, object, is not the only possible one. But that's a detail that doesn't affect what I'm saying here.)

At the level of Python code, however, there are all sorts of ways that you can abuse the "type system" in the sense of using user-defined classes in ways that were not intended or contemplated by the language designers. For example, you can set the __class__ attribute of an instance on the fly, dynamically changing the class of an object (at the level of Python code). This is not recommended, but it can be done (and in some rare cases it might actually be useful). In this sense Python's typing is weak, not strong; a strongly typed language would not let you do such things.
 
  • Like
Likes sysprog
  • #11
The main point of these 3 examples is to highlight is the difference between "instance variables" and "class variables".

Instance variables have values which are unique to a single instance of a class while the values of class variables are shared across all instances of the class.

Example 1 is using a method to create two instance variables. It is encapsulating the initialization procedure so it can be shared across instances of the class.

Example 2 is also creating two instance variables but this time outside the class unencapsulated.

Example 3 is creating two instance variables and two class variables and illustrating that the instance variable takes precedence over the class variable when accessed through the instance. You could go further with this example and instantiate another instance without calling the set method and see that it prints out the class variables. You could also print out MyClass.x and see 0.
 
Last edited:
  • Like
Likes FactChecker and phinds

1. What are the three listings being compared?

The three listings being compared could refer to any type of data, such as product listings, job listings, or real estate listings. It is important to specify which specific listings are being compared in order to accurately assess any potential differences.

2. Is there a significant difference between the three listings?

The answer to this question would depend on the specific data being compared. It is important to analyze the data and determine if there are any notable differences between the three listings in order to draw any conclusions.

3. How can I determine if there are any differences between the three listings?

To determine if there are any differences between the three listings, one could conduct a statistical analysis, compare key metrics or variables, or visually compare the data through graphs or charts. It is important to use a reliable and valid method of analysis to accurately determine any differences.

4. Why is it important to compare these three listings?

Comparing these three listings can provide valuable insights and information, such as identifying trends, understanding market dynamics, or making informed decisions. It can also help identify any discrepancies or errors in the data.

5. Can the differences between the three listings be explained?

Yes, the differences between the three listings can be explained through further analysis and investigation. It is important to consider external factors, such as time period, location, or sample size, that may impact the data and potentially explain any differences.

Suggested for: Is there any difference between these three listings?

Back
Top