Is there any difference between these three listings?

  • Thread starter user366312
  • Start date

user366312

Gold Member
66
2
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?
 
15,171
4,824
What do YOU think and why?
 

user366312

Gold Member
66
2
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?
 
15,171
4,824
I think # is a matter of style, probably more comfortable for long-time non-OOP programmers.
 
25,764
6,611
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.

What is the **theoretical** difference between these three listings?
What do you mean by "theoretical"?
 
25,764
6,611
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.
 

DavidSnider

Gold Member
454
107
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.
 

FactChecker

Science Advisor
Gold Member
2018 Award
4,979
1,748
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.
 

DavidSnider

Gold Member
454
107
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.
 
25,764
6,611
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.
 

DavidSnider

Gold Member
454
107
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:

Want to reply to this thread?

"Is there any difference between these three listings?" You must log in or register to reply here.

Related Threads for: Is there any difference between these three listings?

Replies
12
Views
1K
Replies
4
Views
2K
Replies
5
Views
3K
Replies
1
Views
2K

Physics Forums Values

We Value Quality
• Topics based on mainstream science
• Proper English grammar and spelling
We Value Civility
• Positive and compassionate attitudes
• Patience while debating
We Value Productivity
• Disciplined to remain on-topic
• Recognition of own weaknesses
• Solo and co-op problem solving
Top