Python private class fields, how to make? [duplicate] - python

This question already has answers here:
Does Python have “private” variables in classes?
(15 answers)
Closed 9 years ago.
I'm beginner. In Delphi I can make private field in class: moving it to private section. So ClassVar.Field doesn't exist out of class.
In Python, if I make class
class CName:
testname = 10
then testname can be accessed always. How can I make a field "private"?

You can't!
Naming fields with two underscores will hide it (generate a new name) but you will always be able to access it. Try __testname = 10

Related

How to avoid hidden bugs caused by redefining an variable in Python [duplicate]

This question already has answers here:
When should an attribute be private and made a read-only property? [closed]
(10 answers)
Closed 3 years ago.
If we have the following code:
class Dog:
breed = "Hamster"
color = "Blue"
.... tons of properties ...
favoriteLanguage= "Python"
In another script, we don't realize that Dog class already has favoriteLanguage, we might do something by accident:
luna = Dog()
luna.favoriteLanguage = "C++"
We supposed to keep favoriteLanguage as a public variable, a const or something cannot be modified like that, because it might cause hidden bug. The best way is to get error/warning to notice this. How can we do this in Python?
You can define a setter method.
#property
def favoriteLanguage(self):
return self.__favoriteLanguage
#table_name.setter
def favoriteLanguage(self, favorite_language):
if not self.favoriteLanguage:
self.__favoriteLanguage = favorite_language
else:
raise AttributeError

Why create an empty class, then instantiate it and set some attributes? [duplicate]

This question already has answers here:
Empty class object in Python
(4 answers)
Closed 7 years ago.
html2txt contains the following code:
class Storage: pass
options = Storage()
options.google_doc = False
options.ul_item_mark = '*'
I've not seen such an approach before. What's the benefit/use of this approach over setting up the attributes in __init__(), and is a class even necessary here?
Suppose you want to store some collection of named data. You could use a dict but you like the look of dotted attributes in a class object. Just create the most boring class possible and use python's native attribute assignment to do the trick. It is usually a question of aesthetics.
If you know the attributes ahead of time you can use namedtuples for this kind of functionality.
From the python docs:
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

get variable name of instance [duplicate]

This question already has answers here:
Simpler way to create dictionary of separate variables?
(27 answers)
How can you print a variable name in python? [duplicate]
(8 answers)
Closed 8 years ago.
Can a Python instance get the name of the variable which is used to access the object?
This example code shows what I need:
foo=MyClass()
foo.get_name() --> 'foo'
bar=foo
bar.get_name() --> 'bar'
I know that this is black magic and not clean code. I just want to know if it is possible.
I know that bar.__name__ returns the name, but I need it inside an own method.
How can get_name() be implemented?
This is not a duplicate of questions which answer is __name__

List of member variables in a class. [duplicate]

This question already has answers here:
Why is python ordering my dictionary like so? [duplicate]
(3 answers)
Closed 9 years ago.
I am trying to get a list of member variables of a class.
class Book(object):
def __init__(self):
self.title='Inferno'
self.author = 'Dan Brown'
self.publisher= 'DoubleDay'
self.pages=480
bk = Book()
p=bk.__dict__
print p.keys()
The output is:
['publisher', 'author', 'pages', 'title']
I am curious here as the list is neither printedalphabetically nor according to the way I listed the class variables. So in what way does python print it out?
Its completely arbitrary, because it is a dictionary, and a dict is unordered.
(Well, not arbitrary, but more-or-less random, according to the way the computer stores the data).
Python stores class variables in a dict. This is an unordered data structure, so Python is free to choose whatever order it likes.

Test if a class is inherited from another [duplicate]

This question already has answers here:
How do I check (at runtime) if one class is a subclass of another?
(10 answers)
Closed 4 years ago.
This question is more Python related than Django related. I want to test write a test for this function that I am using to get a Django form dynamically with the fields I set.
def quiz_form_factory(question):
properties = {
'question': forms.IntegerField(widget=forms.HiddenInput, initial=question.id),
'answers': forms.ModelChoiceField(queryset=question.answers_set)
}
return type('QuizForm', (forms.Form,), properties)
I want to test if, the QuizForm class returned is inherited from forms.Form.
Something like:
self.assertTrue(QuizForm isinheritedfrom forms.Form) # I know this does not exist
Is there any way to do this?
Use issubclass(myclass, parentclass).
In your case:
self.assertTrue( issubclass(QuizForm, forms.Form) )
Use the built-in issubclass function. e.g.
issubclass(QuizForm, forms.Form)
It returns a bool so you can use it directly in self.assertTrue()

Categories