Python alter attribute of instance during initialization Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding Python super() with __init__() methodsHow to know if an object has an attribute in PythonProper way to declare custom exceptions in modern Python?Does Python have a string 'contains' substring method?
Sorting numerically
List *all* the tuples!
Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?
Is there a service that would inform me whenever a new direct route is scheduled from a given airport?
Can a non-EU citizen traveling with me come with me through the EU passport line?
What are the pros and cons of Aerospike nosecones?
What happens to sewage if there is no river near by?
How do I mention the quality of my school without bragging
Why is "Captain Marvel" translated as male in Portugal?
What is the correct way to use the pinch test for dehydration?
Disable hyphenation for an entire paragraph
When to stop saving and start investing?
What's the purpose of writing one's academic bio in 3rd person?
What would be the ideal power source for a cybernetic eye?
Check which numbers satisfy the condition [A*B*C = A! + B! + C!]
How much radiation do nuclear physics experiments expose researchers to nowadays?
How to find all the available tools in macOS terminal?
Should I use Javascript Classes or Apex Classes in Lightning Web Components?
Is the address of a local variable a constexpr?
Why does Python start at index 1 when iterating an array backwards?
Should I discuss the type of campaign with my players?
Are my PIs rude or am I just being too sensitive?
Stars Make Stars
If Jon Snow became King of the Seven Kingdoms what would his regnal number be?
Python alter attribute of instance during initialization
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding Python super() with __init__() methodsHow to know if an object has an attribute in PythonProper way to declare custom exceptions in modern Python?Does Python have a string 'contains' substring method?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
Is it possible to alter attributes of instances during its initialization?
E. G the following code.
class Sensor() :
def __init__(self) :
self.name = 'pressure'
Sensor1 = Sensor(name='pH')
Would that be possible?
python class
add a comment |
Is it possible to alter attributes of instances during its initialization?
E. G the following code.
class Sensor() :
def __init__(self) :
self.name = 'pressure'
Sensor1 = Sensor(name='pH')
Would that be possible?
python class
add a comment |
Is it possible to alter attributes of instances during its initialization?
E. G the following code.
class Sensor() :
def __init__(self) :
self.name = 'pressure'
Sensor1 = Sensor(name='pH')
Would that be possible?
python class
Is it possible to alter attributes of instances during its initialization?
E. G the following code.
class Sensor() :
def __init__(self) :
self.name = 'pressure'
Sensor1 = Sensor(name='pH')
Would that be possible?
python class
python class
edited Mar 8 at 16:23
Carlos Gonzalez
621718
621718
asked Mar 8 at 16:19
Leo blublaLeo blubla
156
156
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
You need to explicitly declare you accept a name
argument and then you need to explicitly update the appropriate attribute:
class Sensor():
def __init__(self, name='pressure'):
self.name = name
Notice that I'm using 'pressure'
as a default value for the name
argument in case the consumer does not provide it:
a = Sensor()
print(a.name) # 'pressure'
b = Sensor(name='sensor')
print(b.name) # 'sensor'
name
can also be provided as a positional argument:
c = Sensor('some_name')
print(c.name) # 'some_name'
A more generic approach
There's also a more generic approach (if the use cases requires it), which involves creating the attributes dynamically:
class Sensor():
def __init__(self, **kwargs):
for attr, value in kwargs.items():
setattr(self, attr, value)
Then you can do something like:
d = Sensor(name='foo', temperature=70, active=True)
print(d.name) # 'foo'
print(d.temperature) # 70
print(d.active) # True
add a comment |
Not like that, if you want to set the attribute you would have to do something like:
class Sensor() :
def __init__(self, name='pressure') :
self.name = name
Sensor1 = Sensor(name='pH')
If not provided the name would be pressure
but if name is given in the initialization it will be set to the one provided.
add a comment |
You will need to give a way to pass those and set default values. In your example, you just need to add a default.
class Sensor() :
def __init__(self,name='pressure') :
self.name = name
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55067097%2fpython-alter-attribute-of-instance-during-initialization%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
You need to explicitly declare you accept a name
argument and then you need to explicitly update the appropriate attribute:
class Sensor():
def __init__(self, name='pressure'):
self.name = name
Notice that I'm using 'pressure'
as a default value for the name
argument in case the consumer does not provide it:
a = Sensor()
print(a.name) # 'pressure'
b = Sensor(name='sensor')
print(b.name) # 'sensor'
name
can also be provided as a positional argument:
c = Sensor('some_name')
print(c.name) # 'some_name'
A more generic approach
There's also a more generic approach (if the use cases requires it), which involves creating the attributes dynamically:
class Sensor():
def __init__(self, **kwargs):
for attr, value in kwargs.items():
setattr(self, attr, value)
Then you can do something like:
d = Sensor(name='foo', temperature=70, active=True)
print(d.name) # 'foo'
print(d.temperature) # 70
print(d.active) # True
add a comment |
You need to explicitly declare you accept a name
argument and then you need to explicitly update the appropriate attribute:
class Sensor():
def __init__(self, name='pressure'):
self.name = name
Notice that I'm using 'pressure'
as a default value for the name
argument in case the consumer does not provide it:
a = Sensor()
print(a.name) # 'pressure'
b = Sensor(name='sensor')
print(b.name) # 'sensor'
name
can also be provided as a positional argument:
c = Sensor('some_name')
print(c.name) # 'some_name'
A more generic approach
There's also a more generic approach (if the use cases requires it), which involves creating the attributes dynamically:
class Sensor():
def __init__(self, **kwargs):
for attr, value in kwargs.items():
setattr(self, attr, value)
Then you can do something like:
d = Sensor(name='foo', temperature=70, active=True)
print(d.name) # 'foo'
print(d.temperature) # 70
print(d.active) # True
add a comment |
You need to explicitly declare you accept a name
argument and then you need to explicitly update the appropriate attribute:
class Sensor():
def __init__(self, name='pressure'):
self.name = name
Notice that I'm using 'pressure'
as a default value for the name
argument in case the consumer does not provide it:
a = Sensor()
print(a.name) # 'pressure'
b = Sensor(name='sensor')
print(b.name) # 'sensor'
name
can also be provided as a positional argument:
c = Sensor('some_name')
print(c.name) # 'some_name'
A more generic approach
There's also a more generic approach (if the use cases requires it), which involves creating the attributes dynamically:
class Sensor():
def __init__(self, **kwargs):
for attr, value in kwargs.items():
setattr(self, attr, value)
Then you can do something like:
d = Sensor(name='foo', temperature=70, active=True)
print(d.name) # 'foo'
print(d.temperature) # 70
print(d.active) # True
You need to explicitly declare you accept a name
argument and then you need to explicitly update the appropriate attribute:
class Sensor():
def __init__(self, name='pressure'):
self.name = name
Notice that I'm using 'pressure'
as a default value for the name
argument in case the consumer does not provide it:
a = Sensor()
print(a.name) # 'pressure'
b = Sensor(name='sensor')
print(b.name) # 'sensor'
name
can also be provided as a positional argument:
c = Sensor('some_name')
print(c.name) # 'some_name'
A more generic approach
There's also a more generic approach (if the use cases requires it), which involves creating the attributes dynamically:
class Sensor():
def __init__(self, **kwargs):
for attr, value in kwargs.items():
setattr(self, attr, value)
Then you can do something like:
d = Sensor(name='foo', temperature=70, active=True)
print(d.name) # 'foo'
print(d.temperature) # 70
print(d.active) # True
edited Mar 8 at 17:00
answered Mar 8 at 16:28
Matias CiceroMatias Cicero
13.6k842104
13.6k842104
add a comment |
add a comment |
Not like that, if you want to set the attribute you would have to do something like:
class Sensor() :
def __init__(self, name='pressure') :
self.name = name
Sensor1 = Sensor(name='pH')
If not provided the name would be pressure
but if name is given in the initialization it will be set to the one provided.
add a comment |
Not like that, if you want to set the attribute you would have to do something like:
class Sensor() :
def __init__(self, name='pressure') :
self.name = name
Sensor1 = Sensor(name='pH')
If not provided the name would be pressure
but if name is given in the initialization it will be set to the one provided.
add a comment |
Not like that, if you want to set the attribute you would have to do something like:
class Sensor() :
def __init__(self, name='pressure') :
self.name = name
Sensor1 = Sensor(name='pH')
If not provided the name would be pressure
but if name is given in the initialization it will be set to the one provided.
Not like that, if you want to set the attribute you would have to do something like:
class Sensor() :
def __init__(self, name='pressure') :
self.name = name
Sensor1 = Sensor(name='pH')
If not provided the name would be pressure
but if name is given in the initialization it will be set to the one provided.
edited Mar 8 at 16:32
answered Mar 8 at 16:27
Carlos GonzalezCarlos Gonzalez
621718
621718
add a comment |
add a comment |
You will need to give a way to pass those and set default values. In your example, you just need to add a default.
class Sensor() :
def __init__(self,name='pressure') :
self.name = name
add a comment |
You will need to give a way to pass those and set default values. In your example, you just need to add a default.
class Sensor() :
def __init__(self,name='pressure') :
self.name = name
add a comment |
You will need to give a way to pass those and set default values. In your example, you just need to add a default.
class Sensor() :
def __init__(self,name='pressure') :
self.name = name
You will need to give a way to pass those and set default values. In your example, you just need to add a default.
class Sensor() :
def __init__(self,name='pressure') :
self.name = name
answered Mar 8 at 16:28
Polkaguy6000Polkaguy6000
693513
693513
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55067097%2fpython-alter-attribute-of-instance-during-initialization%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown