Is it possible to access multiple object's property created from same class?
Is it possible?, I need to find difference between two object's property value created from same class. For example:
class Category {
public $value1;
public $value2;
public $result;
public function calc($input1, $input2){
$this->value1 = $input1;
$this->value1 = $input2;
$this->result = $this->value1 * $this->value2;
}
}
class SpecialCategory extends Category {
public function calcDif() {
$this->result = $current->result - $prior->result;
}
}
$current = new Category();
$current->calc("10", "5");
$prior = new Category();
$prior->calc("5", "4");
$difference = new SpecialCategory();
$difference->calcDif();
echo $difference->result;
I want to find the difference between same property in difference object but created from same class, the error message is undefined variable
in $this->result = $current->result - $prior->result;
See also questions close to this topic
-
image gallery with filter by year from mysql database
I have a mysql table of images with columns
Heading
,Year
andImage_link
. Years are in YYYY format like 1988, 1992, 1994,1995, 1999, 2013 etc (Not serially all years are there..random are..)I want to display images with year-wise buttons and one button for All. I mean When All is clicked, All images will be shown.. If specific year button is clicked, images with that year should be shown...
I googled for it and I got Portfolio Image Gallery, But examples were with static data. I couldn't find mysql php examples for the same.
I tried it with group by mysql_query but some how I could not make it.
data is fetched from mysql with no problem.. I am stuck How to create yearwise filter buttons and display images related to that year.
Your help is appreciated.
Present non-working code is as follows as I got stuck here How to work on it.......
<?php $query = "select * from image_table group by year order by year asc"; $numrows = $database->num_rows($query); // wrapper class is used if($numrows !=0){ $result = $database->get_results($query); // wrapper class is used foreach($result as $data){ $year = $data['year']; ?> <div align="center"> <button class="btn btn-default filter-button" data-filter="all">All</button> <button class="btn btn-default filter-button" data-filter="<?php echo $year;?>"><?php echo $year;?></button> </div> <br/> <div class="gallery_product col-lg-4 col-md-4 col-sm-4 col-xs-6 filter <?php echo $data['year'];?>"> <img src="url_for_image_from_mysql_row" class="img-responsive"> </div> <?php } } ?>
-
Output dynamic "div" for every 1.dimension in Array
We try to build a rudimential forum with PHP and MySQL for a school project. We have created a MySQL table named "comments". We try to fetch everything from the table "comments" into an array with:
$sthtitel = $pdo->prepare("SELECT * FROM comments ORDER BY comment_id "); $sthtitel->execute(); $result = $sthtitel->fetchAll();
Display the Array like;
<div class="comment-wrapper"> <div class="comment0">Headline</div> <div class="box" id="box1"> <div class="topic" id="comment1"> <div class="titel"><?php echo $result[0]['comment_titel']; echo $result[0]['comment'];?> <br></div> </div> </div> </div>
That works fine.. But we want to display the div "comment-wrapper" dynamically, that a new comment appears automatically.
-
Fixing Column values in MySQL table
I have a subtitle database website where users can upload a subtitle file to a subtitle database! In order not to duplicate a friend made me another table where 2 Code abbreviations at the end of the file name will be added when saving each subtitle for each specific subtitle in a specific language but I have problem
Everything is fine and works fine for languages where only one language name is written in the table but where two or three language names are written in the table, it does not work at all, whether the language names are not written in the table as it should or what could be the problem ? Here is the table SQL file (for example the languages that doesnt work : ('Gaelic; Scottish Gaelic', 'gd') or ('Spanish; Castilian', 'es') etc..:
-- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Dec 08, 2019 at 11:22 PM -- Server version: 10.1.43-MariaDB-cll-lve -- PHP Version: 7.2.7 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `xxxx_xxx` -- -- -------------------------------------------------------- -- -- Table structure for table `xxxx_xxxx` -- CREATE TABLE `xxxxx_xxxxx` ( `language` varchar(44) NOT NULL, `code` varchar(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `xxxx_xxxx` -- INSERT INTO `language_code` (`language`, `code`) VALUES ('Abkhazian', 'ab'), ('Afar', 'aa'), ('Afrikaans', 'af'), ('Albanian', 'sq'), ('Amharic', 'am'), ('Arabic', 'ar'), ('Aragonese', 'an'), ('Armenian', 'hy'), ('Assamese', 'as'), ('Avestan', 'ae'), ('Aymara', 'ay'), ('Azerbaijani', 'az'), ('Bashkir', 'ba'), ('Basque', 'eu'), ('Belarusian', 'be'), ('Bengali', 'bn'), ('Bihari', 'bh'), ('Bislama', 'bi'), ('Bosnian', 'bs'), ('Breton', 'br'), ('Bulgarian', 'bg'), ('Burmese', 'my'), ('Catalan', 'ca'), ('Chamorro', 'ch'), ('Chechen', 'ce'), ('Chinese', 'zh'), ('Church Slavic; Slavonic; Old Bulgarian', 'cu'), ('Chuvash', 'cv'), ('Cornish', 'kw'), ('Corsican', 'co'), ('Croatian', 'hr'), ('Czech', 'cs'), ('Danish', 'da'), ('Divehi; Dhivehi; Maldivian', 'dv'), ('Dutch', 'nl'), ('Dzongkha', 'dz'), ('English', 'en'), ('Esperanto', 'eo'), ('Estonian', 'et'), ('Faroese', 'fo'), ('Fijian', 'fj'), ('Finnish', 'fi'), ('French', 'fr'), ('Gaelic; Scottish Gaelic', 'gd'), ('Galician', 'gl'), ('Georgian', 'ka'), ('German', 'de'), ('Greek, Modern (1453-)', 'el'), ('Guarani', 'gn'), ('Gujarati', 'gu'), ('Haitian; Haitian Creole', 'ht'), ('Hausa', 'ha'), ('Hebrew', 'he'), ('Herero', 'hz'), ('Hindi', 'hi'), ('Hiri Motu', 'ho'), ('Hungarian', 'hu'), ('Icelandic', 'is'), ('Ido', 'io'), ('Indonesian', 'id'), ('Interlingua (International Auxiliary Languag', 'ia'), ('Interlingue', 'ie'), ('Inuktitut', 'iu'), ('Inupiaq', 'ik'), ('Irish', 'ga'), ('Italian', 'it'), ('Japanese', 'ja'), ('Javanese', 'jv'), ('Kalaallisut', 'kl'), ('Kannada', 'kn'), ('Kashmiri', 'ks'), ('Kazakh', 'kk'), ('Khmer', 'km'), ('Kikuyu; Gikuyu', 'ki'), ('Kinyarwanda', 'rw'), ('Kirghiz', 'ky'), ('Komi', 'kv'), ('Korean', 'ko'), ('Kuanyama; Kwanyama', 'kj'), ('Kurdish', 'ku'), ('Lao', 'lo'), ('Latin', 'la'), ('Latvian', 'lv'), ('Limburgan; Limburger; Limburgish', 'li'), ('Lingala', 'ln'), ('Lithuanian', 'lt'), ('Luxembourgish; Letzeburgesch', 'lb'), ('Macedonian', 'mk'), ('Malagasy', 'mg'), ('Malay', 'ms'), ('Malayalam', 'ml'), ('Maltese', 'mt'), ('Manx', 'gv'), ('Maori', 'mi'), ('Marathi', 'mr'), ('Marshallese', 'mh'), ('Moldavian', 'mo'), ('Mongolian', 'mn'), ('Nauru', 'na'), ('Navaho, Navajo', 'nv'), ('Ndebele, North', 'nd'), ('Ndebele, South', 'nr'), ('Ndonga', 'ng'), ('Nepali', 'ne'), ('Northern Sami', 'se'), ('Norwegian', 'no'), ('Norwegian Bokmal', 'nb'), ('Norwegian Nynorsk', 'nn'), ('Nyanja; Chichewa; Chewa', 'ny'), ('Occitan (post 1500); Provencal', 'oc'), ('Oriya', 'or'), ('Oromo', 'om'), ('Ossetian; Ossetic', 'os'), ('Pali', 'pi'), ('Panjabi', 'pa'), ('Persian', 'fa'), ('Polish', 'pl'), ('Portuguese', 'pt'), ('Pushto', 'ps'), ('Quechua', 'qu'), ('Raeto-Romance', 'rm'), ('Romanian', 'ro'), ('Rundi', 'rn'), ('Russian', 'ru'), ('Samoan', 'sm'), ('Sango', 'sg'), ('Sanskrit', 'sa'), ('Sardinian', 'sc'), ('Serbian', 'sr'), ('Shona', 'sn'), ('Sichuan Yi', 'ii'), ('Sindhi', 'sd'), ('Sinhala; Sinhalese', 'si'), ('Slovak', 'sk'), ('Slovenian', 'sl'), ('Somali', 'so'), ('Sotho, Southern', 'st'), ('Spanish; Castilian', 'es'), ('Sundanese', 'su'), ('Swahili', 'sw'), ('Swati', 'ss'), ('Swedish', 'sv'), ('Tagalog', 'tl'), ('Tahitian', 'ty'), ('Tajik', 'tg'), ('Tamil', 'ta'), ('Tatar', 'tt'), ('Telugu', 'te'), ('Thai', 'th'), ('Tibetan', 'bo'), ('Tigrinya', 'ti'), ('Tonga (Tonga Islands)', 'to'), ('Tsonga', 'ts'), ('Tswana', 'tn'), ('Turkish', 'tr'), ('Turkmen', 'tk'), ('Twi', 'tw'), ('Uighur', 'ug'), ('Ukrainian', 'uk'), ('Urdu', 'ur'), ('Uzbek', 'uz'), ('Vietnamese', 'vi'), ('Volapuk', 'vo'), ('Walloon', 'wa'), ('Welsh', 'cy'), ('Western Frisian', 'fy'), ('Wolof', 'wo'), ('Xhosa', 'xh'), ('Yiddish', 'yi'), ('Yoruba', 'yo'), ('Zhuang; Chuang', 'za'), ('Zulu', 'zu'); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-
Meta-programming - How to generate class from template when __class__ is used?
I've created class like this to solve issue with signature and feature_names:
import copy from sklearn.feature_selection import VarianceTreshold class VarianceThresholdN(VarianceThreshold): def __init__(self, **kwargs): super().__init__(**kwargs) self.feature_names = None #hack from https://stackoverflow.com/questions/51430484/how-to-subclass-a-vectorizer-in-scikit-learn-without-repeating-all-parameters-in def get_params(self, deep=True): params = super().get_params(deep) cp = copy.copy(self) cp.__class__ = VarianceThreshold params.update(cp.__class__.get_params(cp, deep)) return params def fit(self, X, y=None): self.feature_names = list(X.columns) return super().fit(X, y)
Unfortunately, I need to create a lot of classes like this, so a lot of copy-paste and replacing two things:
class VarianceThresholdN(VarianceThreshold):
toclass DifferentClassN(DifferentClass):
andcp.__class__ = VarianceThreshold
tocp.__class__ = DifferentClass
.So there is a clear template, but due to
cp.__class__ = ...
I can't use mix-ins.Probably this code could be generated with jinja templates, but is there any way to avoid it, with some pythonic trick from meta-programming?
-
Finding Object in Array of Arrays based in Sub-Object condition
I need to find a object in java based in the property of its many subojects.
What I currently have is ugly as hell and I'm sure there's a more efficient way to do so. Probably with a library like hamcrest, or maybe directly with Java (my knowledge in Java is not the best).
This is what I have so far:
private HotelResult findHotelResult(List<HotelResult> hotelResultsList, HotelSelection hotelSelection) { for (HotelResult hotelResult : hotelResultsList) { for (RoomOption roomOption : hotelResult.getRoomOptions()) { for (RoomTypeIds roomTypeIds : roomOption.getRoomTypeIds()) { for (RoomRateIds roomRateIds : roomTypeIds.getRoomRateIds()) { if ( roomRateIds.getId().equals(hotelSelection.getResultId()) ) return hotelResult; } } } } (...) }
Thank you in advance.
-
Trying to change a private variable in Python
I am playing around with private and protected variables in Python. I have created this simple class.
class Simple: def __init__(self,foo): self.__foo = foo def print_foo(self): print(self.__foo)
From what I have read, by using the prefix
__
I am marking the variable as private. In fact if I try to access it, it will not work:>> test = Simple(3) >> print(test.__foo) AttributeError: 'Simple' object has no attribute '__foo'
However, it lets me "try" to change the value of the variable form outside the class. The value doesn't really change, but it doesn't raise an error
>> test.__foo = 2 >> test.print_foo() >> print(test.__foo) 3 2
This behavior seems a bit dangerous to me. Am I doing something wrong? Is there a way to raise an error if I try to change the value of a private variable?
-
class attribute setter: TypeError: 'int' object is not callable
I am getting the following error:
Traceback (most recent call last): File ".../TEST.py", line 34, in <module> b.level = 12 # Error File ".../TEST.py", line 23, in level super().level(self, new_level) TypeError: 'int' object is not callable
And here is the code:
class A: def __init__(self): self._level = 0 @property def level(self): return self._level @level.setter def level(self, new_level): self._level = new_level class B(A): def __init__(self): super().__init__() @property def level(self): return self._level @level.setter def level(self, new_level): super().level(self, new_level) a = A() print(a.level) # --> 0 a.level = 12 print(a.level) # --> 0 b = B() print(b.level) # --> 12 b.level = 12 # Error print(b.level) # never reached
I saw that post class method TypeError "Int object not callable" but it did not help me
-
Attribute inheritance on properties fails in C#
I have the following property which has
Inherited
set to true.[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, Inherited = true)] public class InheritedAttribute : Attribute { }
The class DerivedA contains a property which overrides BaseA's virtual property with a
[InheritedAttribute]
tag.public class BaseA { [InheritedAttribute] public virtual int prop { get; set; } } public class DerivedA : BaseA { public override int prop { get; set; } }
Unfortunately, the attribute is not found on
DerivedA.prop
, thus the attribute has not been inherited to the child property.public static void Main() { var propertyInfo = typeof(DerivedA).GetProperties()[0]; // propertyInfo.CustomAttributes is empty // propertyInfo.GetCustomAttributes(true) is empty }
If the attribute is placed on a method instead of a property, as seen in the example code on microsoft's website, the attribute is inherited as expected, and would be found in the
methodInfo.CustomAttributes
.Is attribute inheritance simply not allowed on properties? Or am I missing something else entirely?
-
Backwards compatibility of Python properties
Cant seem to find any answers on here. How exactly is it that properties can be used for their backwards compatibility in OOP as opposed to simply using local instance variables? I have been told that properties can work with older code but do not understand how this would actually work.
Thanks