简体   繁体   中英

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

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 gx None Gx None

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

But I don't want to use self prefix, eg:

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

any idea?

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

When you create g you update G.dat . But you don't update Gx . G.dat and Gx 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 Gx .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM