Jump to content
Sign in to follow this  
Lizwi

Class label

Recommended Posts

Can anyone show me the following here:

1) Object

2) Method

3) Attribute

 

Thanks

Share this post


Link to post
Share on other sites
Posted (edited)
1 hour ago, Lizwi said:

Can anyone show me the following here:

1) Object

2) Method

3) Attribute

In what language?

 

Let's suppose so it's Java:

class Person {
    // this is public attribute/member of object/class
    public String firstName;
    
    // this is protected attribute/member of object/class (accessible from this class and subclasses of this class)
    protected String secretOfPerson;
    
     // this is private attribute/member of object/class (accessible only from this class code: actually never in this example)
    private String topSecretOfPerson;
    
    // public method can be executed from anywhere (with special careful attention from separate thread, than the main thread!)
    public void setFirstName( @NonNull String firstName ) {
        this.firstName = firstName;
    }
    
    // yet another public method
    public @NonNull String getFirstName() {
        return( firstName );
    }
    
    // protected methods can be called only from subclass of this class or from class itself
    protected void operation1() {
    }
    
    // private methods can be called only from this class
    private void operation2() {
    }
}

 

class "Attributes" are often with prefix "m" or "m_" which is shortcut from "member".

In the above example I used the same name for member of object and method argument ("firstName"). Which obviously is conflict. Compiler don't know which is which. They can be distinguished by using "this." for member of object.

 

You can learn the basics of Java language from w3schools

https://www.w3schools.com/java/java_classes.asp

 

Edited by Sensei

Share this post


Link to post
Share on other sites
Quote

// protected methods can be called only from subclass of this class or from class itself

Not correct it doesn't have to be a subclass, protected methods can only be called by classes in the same package or sub packages (folder).

There you go nice python example

# coding = "utf-8"
class Npc(object):

    ##########################################
    #   Static Attributes
    #########################################

    # All instances of the Npc class will only ever have one instance of a Static variable
    static_npc_database = "game_npc_list"
    _max_walk_vertical = 12
    __max_walk_horizontal = 10
    max_run_vertical = 35
    max_run_horizontal = 30

    ##########################################
    #   Static Getters
    ##########################################

    @staticmethod
    def _get_max_walk_horizontal():
        """ static private methods can be called only from instances of this class
        :return the top secret of Npc """
        return Npc.__max_walk_horizontal

    @staticmethod
    def __get_max_walk_vertical():
        """ static protected methods can be called only from classes/subclasses in the same package/module
        :return the secret of Npc """
        return Npc._max_walk_vertical

    @staticmethod
    def get_max_run_horizontal():
        """ public static methods can be called from all classes
        :return the top secret of Npc """
        return Npc.max_run_horizontal

    @staticmethod
    def get_max_run_vertical():
        """ public static methods can be called from all classes
        :return the secret of Npc """
        return Npc.max_run_vertical

    ##########################################
    #   Static Setters
    ##########################################

    @staticmethod
    def _set_max_walk_horizontal(new_max_walk_horizontal):
        """ static private methods can be called only from instances of this class
        :except not string or null """
        if Npc.string_validator(new_max_walk_horizontal):
            Npc.__max_walk_horizontal = new_max_walk_horizontal

    @staticmethod
    def __set_max_walk_vertical(new_max_walk_vertical):
        """ static protected methods can be called only from classes/subclasses in the same package/module
        :except not string or null """
        if Npc.string_validator(new_max_walk_vertical):
            Npc._max_walk_vertical = new_max_walk_vertical

    @staticmethod
    def _set_max_run_horizontal(new_max_run_horizontal):
        """ static private methods can be called only from instances of this class
        :except not string or null """
        if Npc.string_validator(new_max_run_horizontal):
            Npc.__max_run_horizontal = new_max_run_horizontal

    @staticmethod
    def __set_max_run_vertical(new_max_run_vertical):
        """ static protected methods can be called only from classes/subclasses in the same package/module
        :except not string or null """
        if Npc.string_validator(new_max_run_vertical):
            Npc._max_run_vertical = new_max_run_vertical

    #########################################
    #  Static Methods
    ##########################################

    @staticmethod
    def string_validator(variable):
        """
            Validates that a variable is a string
            :param variable: The string
            :return: The result
            :except: Variable is not a string
        """
        if variable is None or type(variable) != str:
            raise Exception("Npc cannot have a null/(non string) variable")
        else:
            return True

    @staticmethod
    def int_validator(variable):
        """
            Validates that a variable is an int
            :param variable: The int
            :return: The result
            :except: Variable is not an int
        """
        if variable is None or type(variable) != int:
            raise Exception("Npc cannot have a null/(non int) variable")
        else:
            return True

    @staticmethod
    def _calculate_movement_value(value, max_value):
        if Npc.int_validator(value):
            if value < max_value:
                return value
            elif value > 0:
                return max_value
            else:
                return -max_value

    #######################
    #  constructor
    #######################

    def __init__(self,
                 first_name: str = "Santa",
                 x_position: int = 100,
                 y_position: int = 100,
                 max_walk_vertical: int = None,
                 max_walk_horizontal: int = None,
                 max_run_vertical: int = None,
                 max_run_horizontal: int = None):
        """
            Npc Constructor (non static variables are defined here)
            :type first_name: str
            :param first_name: The Npc's first-name.
            :type x_position: int
            :param x_position: The Npc's x position.
            :type y_position: int
            :param y_position: The Npc's y position.
        """
        if Npc.string_validator(first_name):
            # this is public attribute/member of object/class
            self.firstName = first_name
        if Npc.int_validator(x_position):
            # this is protected attribute/member of object/class
            # (accessible from this class and subclasses of this class)
            self._x_position = x_position
        if Npc.int_validator(y_position):
            # this is private attribute/member of object/class
            # (accessible only from this class code: actually never in this example)
            self.__y_position = y_position

        if max_walk_vertical is not None and max_walk_vertical < Npc._max_walk_vertical:
            self.max_walk_vertical = max_walk_vertical
        else:
            self.walk_vertical = Npc._max_walk_vertical
        if max_walk_horizontal is not None and max_walk_horizontal < Npc.__max_walk_horizontal:
            self.max_walk_horizontal = max_walk_horizontal
        else:
            self.max_walk_horizontal = Npc.__max_walk_horizontal

        if max_run_vertical is not None and max_run_vertical < Npc.max_run_vertical:
            self.max_run_vertical = max_run_vertical
        else:
            self.max_run_vertical = Npc.max_run_vertical

        if max_run_horizontal is not None and max_run_horizontal < Npc.max_run_horizontal:
            self.max_run_horizontal = max_run_horizontal
        else:
            self.max_run_horizontal = Npc.max_run_horizontal

    #########################################
    #  Getters Methods
    ##########################################

    def get_first_name(self):
        """ yet another public method
        :return the first name of Npc """
        return self.firstName

    def _get_x_position(self):
        """ protected methods can be called only from classes/subclasses in the same package/module
            :return the secret of Npc """
        return self._x_position

    def __get_y_position(self):
        """ private methods can be called only from this class
        :return the top secret of Npc """
        return self.__y_position

    #########################################
    #  Setter Methods
    ##########################################

    def set_first_name(self, first_name: str):
        """ public method can be executed from anywhere (with special careful attention from separate thread,
            than the main thread!)
            :except not string """
        if Npc.string_validator(first_name):
            self.firstName = first_name

    def _set_x_position(self, new_x_position):
        """ protected methods can be called only from classes/subclasses in the same package/module
            :return the secret of Npc """
        if Npc.int_validator(new_x_position):
            self._x_position = new_x_position

    def __set_y_position(self, new_y_position):
        """ private methods can be called only from this class
        :return the top secret of Npc """
        if Npc.int_validator(new_y_position):
            self.__y_position = new_y_position

    #################################################
    #  Methods
    #################################################

    def walk(self, vertical=0, horizontal=0):
        """ An Npc should be able to walk
            :param vertical: The distance to walk vertical
            :param horizontal: The distance to walk horizontal """

        self.__set_y_position(
            self.__get_y_position() + self._calculate_movement_value(vertical, self.max_walk_vertical))
        self._set_x_position(
            self._get_x_position() + self._calculate_movement_value(horizontal, self.max_walk_horizontal))

    def run(self, vertical=0, horizontal=0):
        """ An Npc should be able to run
        :param vertical: The distance to run vertical
        :param horizontal: The distance to run horizontal """
        self.__set_y_position(
            self.__get_y_position() + self._calculate_movement_value(vertical, self.max_run_vertical))
        self._set_x_position(
            self._get_x_position() + self._calculate_movement_value(horizontal, self.max_run_horizontal))


class Teacher(Npc):
    def foo(self):
        self._get_x_position()

    def bar(self):
        self.__get_y_position()


if __name__ == "__main__":
    teacher = Teacher()
    print(teacher.firstName)
    print(teacher.bar())
    try:
        print(teacher.foo())
    except:
        print("cannot get y position here because it is private")
    teacher.run(10, 10)
    print(teacher.bar())

 

Share this post


Link to post
Share on other sites
On 8/9/2019 at 11:03 PM, fiveworlds said:

Not correct it doesn't have to be a subclass, protected methods can only be called by classes in the same package or sub packages (folder).

There is slight difference between C++, I am used to, and Java in this area:

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

"The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package."

 

 

On 8/9/2019 at 11:03 PM, fiveworlds said:

There you go nice python example

Q: "How can I define a method in a python class that is protected and only subclasses can see it?"

A: "Python does not support access protection as C++/Java/C# does. Everything is public. The motto is, "We're all adults here." Document your classes, and insist that your collaborators read and follow the documentation.

The culture in Python is that names starting with underscores mean, "don't use these unless you really know you should." You might choose to begin your "protected" methods with underscores. But keep in mind, this is just a convention, it doesn't change how the method can be accessed.

Names beginning with double underscores (__name) are mangled, so that inheritance hierarchies can be built without fear of name collisions. Some people use these for "private" methods, but again, it doesn't change how the method can be accessed.

The best strategy is to get used to a model where all the code in a single process has to be written to get along."

https://stackoverflow.com/questions/11483366/protected-method-in-python

 

Share this post


Link to post
Share on other sites
Quote

There is slight difference between C++,

There really isn't though c++ is more complicated with header files etc. Private variables are accessible by subclasses, protected variables/methods can only be called by classes in the same package or sub packages (folder).

namespace second_space {
	class Box {
		private:
			class B {
				protected:
					double length = 10;
			};
		public:
			class Car : B {
			public:
				double dimensions() {
					return B::length;
				};
			};
			double height=4;
			double getDimensions(void);
		protected:
			double breadth = 7;
	};
	double Box::getDimensions() {
		Car car = Car();
		return car.dimensions();
	}
	class ExtendedBox:Box {
		public:
			double test(void);
	};
	double ExtendedBox::test() {
		return breadth;
	}
	class Bar {
		double test(void);
	};
	double Bar::test(void) {
		Box box = Box();
		return box.height;
		//return box.breadth; compile error
	}
}

int main() {
	// Calls function from first name space.
	second_space::Box box;
	cout << box.getDimensions() << endl;
	second_space::ExtendedBox extendedBox;
	cout << extendedBox.test() << endl;
	Bar::ExtendedCar extendedCar;
	cout << extendedCar.test() << endl;
	return 0;
}
Quote

Python does not support access protection as C++/Java/C# does. Everything is public.

Everything is public in Java, C# etc via reflection... I don't see the difference they all use some form of obfuscation in their own proprietary way.

 

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.