PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 25, 2022

[FIXED] How can I change a variable in a child class so that its dependent variables can also be changed?

 October 25, 2022     class, oop, python, python-3.x     No comments   

Issue

Does anyone know if it is even possible to change the inherited variables of the parent class by changing a variable in a child class? Without declaring them in the __init__ child?

class Foo(object):
    def __init__(self):
        self.data = "abc"
        self.data_2 = self.data

class Bar(Foo):
    def __init__(self):
        super(Bar, self).__init__()
        self.data = "def"

f = Foo()
b = Bar()

print(f.data_2)  # --> abc
print(b.data_2)  # --> abc

But I expect to get:

print(f.data_2)  # --> abc
print(b.data_2)  # --> def

Solution

this solves the issue if you don't want to accept data as an argument to your init func as someone pointed out above

class Foo(object):
    def __init__(self):
        self.data = "abc"

    @property
    def data_2(self):
        return self.data

class Bar(Foo):
    def __init__(self):
        super(Bar, self).__init__()
        self.data = "def"

f = Foo()
b = Bar()

print(f.data_2)
print(b.data_2)


Answered By - Sassy
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing