I have a question for Python class.

Asked 2 years ago, Updated 2 years ago, 19 views

The Python class part is different no matter how much I look at it ㅜ<

class test1:
    def __init__(self):
        self.a = 'a'
    def test1_1(self):
        self.b = 'b'
        return self.b

class test2:
    def __init__(self):
        self.c = 'c'
    def test2_1(self):
        self.d = 'd'
        cls.a = 9999
        cls.b = 8888
        return self.d

cls = test1()
print(cls.a)
print(cls.test1_1())
print(test2().c)
print(test2().test2_1())
print(cls.a)
print(cls.test1_1())

self on this part.I wonder how I can change the value of b to '8888'.

python

2022-09-22 14:56

1 Answers

We recommend OOP's learning in other languages than Python.

Python's OOP is coldly prototype-level.

For example, it is not encapsulated. __It doesn't mean you can't access it twice. You can just change the name by name mangling, so you can access it as much as you want.

What the questioner is confused is that the instance variable is self. It seems to confuse the point that it starts with . In the example below, self is the same as this in another language. Languages such as c++, Java, and c# usually automatically insert the first parameter of the method, this.

In the example below, to access variable b, self.b = 'b' must be run before it can be accessed from the instance (cls).

In [1]: class test1: 
   ...:     ...:     def __init__(self): 
   ...:         ...:         self.a = 'a' 
   ...:     ...:     def test1_1(self): 
   ...:         ...:         self.b = 'b' 
   ...:         ...:         return self.b 
   ...:                                                                         

In [2]: cls = test1()                                                           

In [3]: cls.test1_1() #self.b = 'b' executed                                                           
Out[3]: 'b'

In [5]: cls.b #Accessible                                                                   
Out[5]: 'b'

In [6]: cls.b = 'bb' #changeable                                                            

In [7]: cls.b                                                                   
Out[7]: 'bb'

In [8]: cls2 = test1()                                                                                                    

In [9]: instance variable b does not exist because cls2.b #self.b is not executed                                                                                                        
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-d2c349d5bcec> in <module>
----> 1 cls2.b

AttributeError: 'test1' object has no attribute 'b'


2022-09-22 14:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.