+ 2
How to access class variables?Give me good resources to learn oops in Python
class User: name="seenu" def __init__(self): self.name = "srini" def sayHello(self): print("Welcome to Guru99, " + self.name)#why error shows when I use name instead of self.name print(User.name)#why error? User1 = User() User1.sayHello() print(User.name)
24 Answers
+ 7
The second errored line belongs to the block of the class itself, and it seems it doesn't know its own name. š
Basically you only made an indentation error. If you either write print(name) (because we're in class User) or you indent the line so that it belongs to the method, your code works.
The first error happens later, when you call the method of the instance.
And the instance doesn't know the class variable name, it only knows its personally stored name, which you access by self.
So if you want to get the class variable, you have to look it up directly with User.name, or you can also write self.__class__.name.
(Has this become any clearer?)
+ 6
Geek, as HonFu said, you need to look for the name in the class itself, with self.name. name on it own will produce errors (outside function), because it has not been defined.
However, in the last line of the class, it's the opposite.
You can't use User.name because User is not an object yet, it is just a class. You must change it to print(name), as you have already defined it in the first line.
+ 6
Aymane Boukrouh Wow... just when I thought Python couldn't be more oĢ¶fĢ¶ Ģ¶aĢ¶ Ģ¶jĢ¶oĢ¶kĢ¶eĢ¶ Ģ¶fĢ¶oĢ¶rĢ¶ compromised as a language, it manages to surprise me still. š¤¦āāļøš
In my original attempt, I placed print(name) below the last class method and got a runtime error.
After you clarified seeing this work, I tested again with the same line placed above the first class method. Low and behold... it friggin worked like some random block of code just placed anywhere it very well pleased. šš¤£
This is just another reason I could never, in good conscience, ever seriously consider Python for any commercial grade large development effort.
+ 6
Ipang I will only share my secret with you if you promise not to reveal this to anyone else. You must be sworn to absolute secrecy.
My secret is...
I used a website to generate the text equivalent containing the strike through font.
https://saijogeorge.com/strikethrough-text-generator/
Remember... I'm trusting you with this secret. š¤«š¤š
+ 4
Aymane Boukrouh I don't believe your # Fix Option 3 would work.
This essentially places a method invocation as a class member, which wouldn't exist in any language I've worked with. This wouldn't work for neither print(User.name) nor print(name). š¤·āāļø
+ 4
David Carroll technically it does work with python, I'm sure of it.
But practically it might not be a good idea, depending on what he really wanted to do.
He defined name instance outside of the methods, so it would like this:
class User:
name = "seenu"
# stuff
print(name)
But again, just like you both said, not practical, and a bad idea.
+ 4
David Carroll, don't you think it's rather more of a matter how well you know the language?
I mean, this strange behaviour wouldn't ever normally come up because you don't write random print lines into a class definition.
But if you do, weird stuff happens.
If a trivial thing like this already disqualifies a language, C should have been abolished decades ago with all its undefined behavior shenanigans. š
+ 4
[Response #4: Part 1 of 4]
HonFu Not at all... my criticism isn't based on my unfamiliarity with some unique language feature or its quirky behavior. Surely I've established some modicum of credibility beyond that of someone as petty and shallow as this. š
I did find it odd to learn how Python supports control statements in the class body. However, this alone isn't enough for me to publicly rebuke such a "beloved" language and dismiss it as one I would ever consider for a large project.
Rather, my criticism runs much deeper as I continue becoming more familiar with the language well beyond the surface semantics.
This has led me to discovering short-sighted compromises that get swept under the carpet by diehard Pythonistas in cult like fashion who willingly drink the Kool-aid served from PEP8, the Pythonic Code Style Guidelines, and other idiomatic expressions like "We're all consenting adults."
+ 4
[Response #4: Part 3 of 4]
It's no secret that OOP in Python was slapped on as an after thought. However, I never considered Python class scoping is possibly being constructed with the same parser used for building function scope, then buried under a bit of syntactic sugar.
While this tight coupling might initially simplify the changes needed for the parser to support OOP classes, it could make it difficult to introduce deviating behavior in the future.
How much of this tight coupling led to existing decisions for the following:
- the strange need to define `cls` and `self` parameters for class and instance methods
- no real support for private variables
- no support for block scopes
- closure scoped variables being read-only
I then came across these two posts that provide additional insight:
http://python-history.blogspot.com/2009/03/how-everything-became-executable.html
- Notes from BDFL himself.
https://medium.com/@makmanalp/python-statements-in-the-body-of-a-class-63664392e062
+ 4
Hehehe I am a good secret keeper David
But it wouldn't be much or even any good now that this is visible for all SoloLearners is it?
You got my word on it ...
Your secret, is safe with me ...
ššš
Big Thanks David Carroll š
+ 3
Youtube - Corey Schafer
+ 3
HonFu I haven't tried it, but which line produces indentation error ? I think that apart from print(User.name) should be print(name), everything should work fine
+ 3
Here are the fixes with comments.
https://code.sololearn.com/cdVPLbU6xjrq/
+ 3
David Carroll you forgot # Fix Option 3:
class User:
# stuff
print(name) # instead of print(User.name)
Isn't this valid as well ?
+ 3
HonFu oh I still don't know what he's trying to do, but you're right I think šš
+ 3
David Carroll, the miraculous ways of Python: Here it does indeed work!
Run this:
class C:
x = 1
print(x)
Basically, since we're in C's body, it knows the names that were defined in its body before, so it can access them like this.
As soon as you put that line into a method, be it instance, static or class, it stops to work. So the line is really only executed once.
+ 3
[Response #4: Part 2 of 4]
In my research, I noticed the following excerpts:
--------
8.6 Function definition
----
A function definition is an executable statement.
https://docs.python.org/3/reference/compound_stmts.html#function-definitions
--------
8.7 Class definition
----
A class definition is an executable statement.
https://docs.python.org/3/reference/compound_stmts.html#class-definitions
----
I couldn't help but wonder why something as core as a class definition would be designed to behave like a special function with nested functions?
Was this intentional? Could it be some brilliant master design that feeble minds like mine can't appreciate without significant study?
Or, could this be based on some short-sighted decision with far reaching implications that would require massive changes in the future?
Has this impacted other language design decisions due to any limitations of having classes tied to functions?
+ 3
[Response #4: Part 4 of 4]
My biggest point in all this speculation is to say my criticism of Python runs much deeper than shallow syntactical preferences or something I consider to be innately different or odd.
It's about the risks from a lack of confidence in the language design decisions and the resulting limitations (known and unknown) we may have to contend with down the road.
Whether my concerns are valid or not, in my experience, contending with lower risk assessments and potential technical debt at any level can still result in critical consequences for large projects. We try to minimize those risks by proactively asking the right questions and thinking through mitigation strategies.
The impact of risks related to selecting a bad language would be far more catastrophic than the risks of selecting the wrong framework, middleware, architecture, or third party library / module.
Given these conditions, I would have to choose another language over Python in any large project for which I'm accountable.
+ 2
Geek sorry I was busy. Did you actually use the print statement inside the class ?