Access an instance variable from child classes
You can use "super" to call parent class initialize block and define instance variable "@var".
In that case you can modify value of this instance variable for another instance. Like this:
class Shape
def initialize ()
@var = "woohoo"
end
end
class Rectangle < Shape
def initialize(l, w)
@length = l
@width = w
super()
end
def area()
print @var
return @length * @width
end
def var=(new_value)
@var = new_value
end
end
a = Rectangle.new(1,1)
a.area
# => woohoo1
a.var = "kaboom"
a.area
# => kaboom1
b = Rectangle.new(2,2)
b.area
# => woohoo4
Or ofc you can use attr_accessorclass Shape
def initialize
@var = "woohoo"
end
end
class Rectangle < Shape
attr_accessor :var
def initialize(l, w)
@length, @width = l, w
super()
end
def area()
print @var
return @length * @width
end
end
a = Rectangle.new(1,1)
a.area
# => woohoo1
a.var = "kaboom"
a.area
# => kaboom1
b = Rectangle.new(2,2)
b.area
# => woohoo4
Python accessing parent class variable as instant variable in child class
So, you need to actually implement the property.
class Human(ABC):
def __new__(cls, *args, **kwargs):
cls.human_name = args[0]
cls.source = f'database_{cls.__name__}'.lower()
return super().__new__(cls)
@property
@abstractmethod
def query(self):
pass
class Company:
class Employee(Human):
@property
def query(self):
return f'SELECT {self.human_name} FROM {self.source};'
# these two functions are just for testing and will not be in the final product
def print_something(self):
print(self.human_name)
def print_source(self):
print(self.source)
e = Company.Employee('John')
print(e.human_name)
print(e.query)
e.print_source()
Note, however, since __new__
creates class variables... this query will always be the same across instances:employee1 = Company.Employee('John')
employee2 = Company.Employee('Jack')
print(employee1.query)
print(employee2.query)
will print:SELECT Jack FROM database_employee;
SELECT Jack FROM database_employee;
How to access parent class variable in child class inside a child method?
When you inherit a class, you also inherit all the public and protected methods and variables from the inherited. So you can just do
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.getName()).append(", ");
builder.append(this.getGender()).append(", ");
return builder.toString();
}
How to access the init variable obtained from parent class into child method in python?
The issue is how you are calling example()
:
child.example()
You're calling the example()
method of the child
class itself; you are not calling that method on an instance of child
. The class itself does not have the self.item
or self.model
properties. Those are set in the constructor (__init__()
). To call the contstructor you have to instantiate a new instance of the child
object:c = child(10, 'blah')
Now that c
is an instance of child
, you can call example()
on the instance now:c.example()
#output: 10
Remember, this works because c
is a reference to a specific instance of the child
class, which you deliberately created previously. child
refers to the class itself; it will not have any self
instance variables, because a class is just a class, its constructor hasn't run because it only runs when you instantiate a class, not when you deal with the class itself.One way to avoid this issue is to adhere to the naming standards in Python. Classes always should be CamelCase
, and variables should all be snake_case
. That way, you can easily tell that child.what_ever()
is calling a method on an instance of a class, and that Child.blah_blah()
is calling a class method.
For a full list of Python naming conventions, see here: https://peps.python.org/pep-0008/
Access parent class instance variable from child class function
By using key-value coding.
Setting:
[self setValue:@"Hello" forKey:@"name"];
Reading:NSString* name = [self valueForKey:@"name"];
[name writeToFile:@"Filename"
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
How to access parent class variable having same name as child variable with child reference outside the child class?
Cast the Child
to Parent
:
System.out.println(((Parent) c).i);
Why does it work?A Child
instance has two fields named i
, one from the Parent
class and one from Child
, and the compiler (not the runtime type of the instance) decides which one gets used. The compiler does this based on the type he sees. So, if the compiler knows it's a Child
instance, he'll produce an accessor for the Child
field. If he only knows it's a Parent
, you get access to the Parent
field.
Some examples:
Parent parent = new Parent();
Child child = new Child();
Parent childAsParent = child;
System.out.println(parent.i); // parent value
System.out.println(child.i); // child value
System.out.println(((Parent) child) .i); // parent value by inline cast
System.out.println(childAsParent.i); // parent value by broader variable type
If the compiler knows it's a Child
, he gives access to the Child
field, if you take this knowledge away (by casting or by storing into a Parent
variable), you get access to the Parent
field.This is confusing, isn't it? It's an invitation for all kinds of nasty misunderstandings and coding mistakes. So it's good advice not to have the same field name in a parent and a child class.
Access child class variable in parent class
There's nothing inherently wrong with this approach. It really depends on the scope and significance of this class, and where its being used. Building a parent class to use implicitly defined attributes is quick, and in many cases perfectly OK. But, sometimes those implicit attributes can get out of hand, and you might want to ensure that anyone making new subclasses has to define those attributes.
There are a couple approaches to this. Some of this may not work depending on what version of Python you are using. I believe the usage of ABC like this works in Python 3.4+.
Python (and many OO languages) have the concept of an Abstract Base Class. This is a class that can never be instantiated, and it enforces that any subclasses must implement methods or properties defined as abtract in order to be instantiated.
Here's how you could provide a make_sound
method, and still be 100% sure that anyone subclassing Animal is indeed making that sound.
from abc import ABC, abstractmethod
class Animal(ABC):
def make_sound(self):
print(self.sound)
@property
@abstractmethod
def sound(self):
""" return the sound the animal makes """
class Dog(Animal):
@property
def sound(self):
return "bark"
class Cat(Animal):
sound = "meow"
class Thing(Animal):
""" Not an animal """
dog = Dog()
dog.make_sound()
cat = Cat()
cat.make_sound()
# thing = Thing() this will raise a TypeError, complaining that its abstract
# animal = Animal() as will this
This shows the many different ways to do this. Using the @property
decorator allows you to set instance variables, or more complex logic, that affect it. Setting sound in the class is (somewhat) like setting a static member in a Java class. Since all cats meow, this probably makes sense in this case. Accessing private instances in child class
As the Method getA()
is inherited, if you call this Method, you'll always invoke the Parent
's Method.
The current Object will be treated as a Parent
and not as a Child
, and the Parent
's a will be returned.
Even though you have your own variable a
, this variable wont override the Parent
's a
. They are different from each other, have different addresses and different values.
If you want getA()
to return Child
's a
, you need to override the Method to return your new variable.
class Child extends Parent {
private int a = 22;
@Override
public int getA(){
return a;
}
}
You could also "go crazy" and do stuff like the following:class Child extends Parent {
private int a = 22;
@Override
public int getA(){
int superA = super.getA();
return a+superA;
}
}
That way you could return the sum of Parent
's and Child
's a
.(Just an example)
Related Topics
Outputting Stdout to a File and Back Again
Permission Error When Trying to Install Rails (Osx)
Why Are Global Methods Allowed to Be Defined Outside of a Class in Ruby
How to Get Source and Variable Values in Ruby Tracebacks
Phusion Passenger with Ruby 1.8 and 1.9
Ruby - Generate All Two Letter Words
Rails/Postgres, 'Foreign Keys' Stored in Array to Create 1-Many Association
Make Headless Browser Stop Loading Page
How to Access Parent/Sibling Module Methods
How to Override a Variable in a Ruby Subclass Without Affecting The Superclass
How to Access Sinatra App on Host Machine with Vagrant Forwarded Ports
Does Rails Support a Neat Way of Listening to a Udp Socket
Segmentation Fault with Ruby 1.8.7
Error Could Not Find I18N-0.7.0 in Any of The Sources
Escaping Strings for Ruby Sqlite Insert