Is there any difference between these three listings?

  • Thread starter Thread starter user366312
  • Start date Start date
  • Tags Tags
    Difference
Click For Summary

Discussion Overview

The discussion revolves around the differences between three code listings that demonstrate various ways of defining and using class attributes in Python. Participants explore both practical and theoretical implications of these approaches, focusing on object-oriented programming concepts, attribute management, and the implications of dynamic typing in Python.

Discussion Character

  • Exploratory
  • Technical explanation
  • Debate/contested

Main Points Raised

  • Some participants question the rationale behind dynamically creating properties on the fly, suggesting it may lead to ambiguity and confusion.
  • There is a discussion about the practical differences between the listings, particularly regarding the potential for AttributeError exceptions if attributes are accessed before being set.
  • One participant emphasizes that listing 3 provides default values for attributes, which can prevent exceptions and is considered good programming practice.
  • Another participant notes that the distinction between instance variables and class variables is crucial, highlighting that instance variables are unique to each class instance while class variables are shared across instances.
  • Some participants express that the classification of Python as a "strong dynamic" language merits clarification, particularly regarding how it handles types and attributes.
  • A later reply mentions that self-modifying code, while potentially useful, can be treacherous, with neural networks as an example where dynamic property creation might be advantageous.

Areas of Agreement / Disagreement

Participants express differing views on the utility and implications of the three listings, with no consensus reached on the best approach or the theoretical differences between them. The discussion remains unresolved regarding the advantages and disadvantages of dynamically creating properties.

Contextual Notes

Participants highlight limitations in understanding the implications of dynamic typing and the potential for errors when attributes are not properly initialized. The discussion also reflects varying perspectives on programming style and language design philosophy.

user366312
Gold Member
Messages
88
Reaction score
3
TL;DR
Is there any difference between these three listings?
[CODE lang="python" title="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)

[/CODE]

[CODE lang="python" title="listing2.py"]
class MyClass:
pass

obj = MyClass()
obj.x = 10
obj.y = "Integer"

print(obj.x)
print(obj.y)

[/CODE]

[CODE lang="python" title="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)



[/CODE] Is there any **practical** difference between these three listings?

What is the **theoretical** difference between these three listings?
 
Technology news on Phys.org
What do YOU think and why?
 
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?
 
I think # is a matter of style, probably more comfortable for long-time non-OOP programmers.
 
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   Reactions: sysprog
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   Reactions: sysprog
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.
 
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   Reactions: sysprog
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   Reactions: 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   Reactions: 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   Reactions: FactChecker and phinds

Similar threads

  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 17 ·
Replies
17
Views
4K
  • · Replies 1 ·
Replies
1
Views
5K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K