Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating classes and variable assignment

Tags:

python

class

I'm trying to understand how classes work a bit better "under the hood" of python.

If I create a class Foo like so

class Foo:
    bar = True

Foo is then directly accessible, such as print(Foo) or print(Foo.bar)

However, if I dynamically create create a class and don't set it to a variable like so

type('Foo',(),{'bar':True})

If done in the interpreter it shows <class '__main__.Foo'>. However, when I try to print Foo it's undefined...NameError: name 'Foo' is not defined

Does this mean that when a class is created the "traditional" way (the first Foo class above), that python automatically sets a variable for the class of the same name? Sort of like this

# I realize this is not valid, just to convey the idea
Foo = class Foo:
    bar = True

If so, then why doesn't python also create a variable named Foo set to class Foo when using type() to create it?

like image 444
user1104854 Avatar asked Mar 30 '26 21:03

user1104854


1 Answers

let's compare your problem with function statements and lambdas (because they play the same role here), consider this function f :

def f ():
  return 1

the above snippet of code is not an expression at all, it is a python statement that creates a function named f returning 1 upon calling it.

let's now do the same thing, but in a different way :

f = lambda : 1

the above snippet of code is a python expression (an assignment) that assigns the symbol f to the lambda expression (which is our function) lambda : 1. if we didn't do the assignment, the lambda expression would be lost, it is the same as writing >>> 1 in the python REPL and then trying after that to reference it.

like image 111
marsouf Avatar answered Apr 02 '26 10:04

marsouf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!