how to initialize python class variables based on a parameter without using self?

118 Views Asked by At

In the folloewing code piece, I want class variable x get value 1000, but it didn't, it gets 'None'.

class G:     
    dat = None
    x = dat
    y = dat+2

    def __init__(self, pdat) -> None:
        G.dat = pdat


    
g = G(1000)
print(g.dat, 'g.x', g.x, 'G.x',G.x)

the result is: 1000 g.x None G.x None

What I really want is to define x, y based on parameter pdat.

But I don't want to use self prefix, e.g.:

 def __init__(self, pdat) -> None:
        self.x = pdat

any idea?

1

There are 1 best solutions below

0
The Photon On
g = G(1000)
print(g.dat, 'g.x', g.x, 'G.x',G.x)

When you create g you update G.dat. But you don't update G.x. G.dat and G.x are two separate objects, and they aren't mutable objects, so changing one won't affect the other.

If you want to see that the class objects are changed, print out G.dat instead of G.x.