Set instance variable name based on argument passed in Python class [duplicate] - python

This question already has answers here:
Why use setattr() and getattr() built-ins?
(5 answers)
Closed 1 year ago.
I want to be able to set the instance variable name in a Python class based on an argument in __init__. Is this possible? Below is what I've tried but that doesn't work.
class my_class:
def __init__(self, var_name):
self['var' + var_name] = var_name

Something like the below.
(Question: why do you want to do that?)
class MyClass:
def __init__(self, var_name):
setattr(self,var_name,var_name)
c = MyClass('jack')
print(c.jack)
output
jack

Related

How to access a class attribute using a string? [duplicate]

This question already has answers here:
obtaining named attributes of self
(2 answers)
Closed 3 years ago.
I want to know how can I access a class attribute using a string. E.g
class Test:
def __init__(self):
# defined self.name here
self.name.person = 1
If I have the program:
a = "person"
b = Test()
How can I print self.name.person using the variable a?
print(b.name.a)
Many thanks!
Python has getattr() as built-in function:
print(getattr(b.name, a))

python #property not overwrite class attribute [duplicate]

This question already has answers here:
Python method name with double-underscore is overridden?
(2 answers)
Closed 6 years ago.
I'm confused with the class attribute. I understand that Python interpreter will search attr inside cls.__dict_ (object attribute) first, If the attribute doesn't exists, it will looking for at class attributes. But in that case I dont know why the result below return None
class A(object):
__attr = None
#property
def attr(self):
return self.__attr
class B(A):
__attr = 1
c = B()
print(c.attr)
# None
This isn't about property, but about the behaviour of attributes prefixed with __. This triggers name mangling, which is almost never what you want and behaves unexpectedly in an inheritance scenario. Don't use it.

Why its necessary to use any string with dot point with self in class python(self.x=x)? [duplicate]

This question already has answers here:
What do __init__ and self do in Python? [duplicate]
(18 answers)
Closed 6 years ago.
I am learning oop in python so i am having some problem to understand sefl keyword properly.
Suppose a program :
class ge:
def __init__(self,a,b):
self.p=a
self.l=b
def ff(self):
aaa=self.p+self.l
print(aaa)
hh=ge(1,2)
hh.ff()
I am confuse why its necessary to use any string with self with dot ? what it means ? Like:
self.a=a and we can change self.a to ay string like self.b , self.c what it means ?? why its necessary ?
My second question is :
what is difference between defining class with parameter and without parameter ?
class hello(object):
def __init__(self,a,v):
self.a=a
self.v=v
def p(self):
f=self.a+self.v
print(f)
he=hello(1,2)
he.p()
if i defined
class hello(object) its working but
if i defined class like:
class hello(): its also working
but if i defined like:
class hello: its also working
what is the difference class hello(object): , class hello(), class hello:
First question : Duplicate of this question
Second question : There is no difference between the different notations. When you use the parenthesis it means that your class inherits from the class between parenthesis.
In python 3, by default every class inherits from the class object. So hello(object): , class hello():, class hello: are totally equivalent.
In python 2 however, you must explicit the inheritance.
Here are more details on how to create classes in python.
self is used to reference the instance of the class, is like this in Java
Duplicated:
When do you use 'self' in Python?

How to get class name from bound method using inspect? [duplicate]

This question already has answers here:
How to get the caller class name inside a function of another class in python?
(6 answers)
Closed 7 years ago.
class MyClass:
def my_method(self):
print(get_context())
MyClass().my_method()
I need get next line:
MyClass::my_method
sys._getframe(2).f_code.co_name gives me only "my_method". How to get also class name?
You can get your classname by calling __class__.__name__ from self.
class Foo(object):
def bar(self):
print(self.__class__.__name__)
Foo().bar()
Output:
Foo

Python : Difference between static methods vs class method [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between #staticmethod and #classmethod in Python?
I am learning OOP in python and came to know about these two methods
It seems that the difference in terms of syntax is that class methods are implicitly passed the class they belong to as their first parameter
class Circle:
all_circles = [] # class variable
#staticmethod
def total_area():
for c in Circle.all_circles: # hardcode class name
# do somethig
#classmethod
def total_area(cls):
for c in cls.all_circles: # no hardcode class name
# do something
I see class method as more flexible since we don't hardcode the class
Question:
- Is it even a question which one is better? #staticmethod or #classmethod?
- what are the scenarios suitable to use of each one of these methods?
A classmethod gets passed the class 'cls' that it was called upon. For more details see: What is the difference between #staticmethod and #classmethod in Python?

Categories

Resources