Search Results

Search found 45620 results on 1825 pages for 'derived class'.

Page 7/1825 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Followup: Python 2.6, 3 abstract base class misunderstanding

    - by Aaron
    I asked a question at Python 2.6, 3 abstract base class misunderstanding. My problem was that python abstract base classes didn't work quite the way I expected them to. There was some discussion in the comments about why I would want to use ABCs at all, and Alex Martelli provided an excellent answer on why my use didn't work and how to accomplish what I wanted. Here I'd like to address why one might want to use ABCs, and show my test code implementation based on Alex's answer. tl;dr: Code after the 16th paragraph. In the discussion on the original post, statements were made along the lines that you don't need ABCs in Python, and that ABCs don't do anything and are therefore not real classes; they're merely interface definitions. An abstract base class is just a tool in your tool box. It's a design tool that's been around for many years, and a programming tool that is explicitly available in many programming languages. It can be implemented manually in languages that don't provide it. An ABC is always a real class, even when it doesn't do anything but define an interface, because specifying the interface is what an ABC does. If that was all an ABC could do, that would be enough reason to have it in your toolbox, but in Python and some other languages they can do more. The basic reason to use an ABC is when you have a number of classes that all do the same thing (have the same interface) but do it differently, and you want to guarantee that that complete interface is implemented in all objects. A user of your classes can rely on the interface being completely implemented in all classes. You can maintain this guarantee manually. Over time you may succeed. Or you might forget something. Before Python had ABCs you could guarantee it semi-manually, by throwing NotImplementedError in all the base class's interface methods; you must implement these methods in derived classes. This is only a partial solution, because you can still instantiate such a base class. A more complete solution is to use ABCs as provided in Python 2.6 and above. Template methods and other wrinkles and patterns are ideas whose implementation can be made easier with full-citizen ABCs. Another idea in the comments was that Python doesn't need ABCs (understood as a class that only defines an interface) because it has multiple inheritance. The implied reference there seems to be Java and its single inheritance. In Java you "get around" single inheritance by inheriting from one or more interfaces. Java uses the word "interface" in two ways. A "Java interface" is a class with method signatures but no implementations. The methods are the interface's "interface" in the more general, non-Java sense of the word. Yes, Python has multiple inheritance, so you don't need Java-like "interfaces" (ABCs) merely to provide sets of interface methods to a class. But that's not the only reason in software development to use ABCs. Most generally, you use an ABC to specify an interface (set of methods) that will likely be implemented differently in different derived classes, yet that all derived classes must have. Additionally, there may be no sensible default implementation for the base class to provide. Finally, even an ABC with almost no interface is still useful. We use something like it when we have multiple except clauses for a try. Many exceptions have exactly the same interface, with only two differences: the exception's string value, and the actual class of the exception. In many exception clauses we use nothing about the exception except its class to decide what to do; catching one type of exception we do one thing, and another except clause catching a different exception does another thing. According to the exception module's doc page, BaseException is not intended to be derived by any user defined exceptions. If ABCs had been a first class Python concept from the beginning, it's easy to imagine BaseException being specified as an ABC. But enough of that. Here's some 2.6 code that demonstrates how to use ABCs, and how to specify a list-like ABC. Examples are run in ipython, which I like much better than the python shell for day to day work; I only wish it was available for python3. Your basic 2.6 ABC: from abc import ABCMeta, abstractmethod class Super(): __metaclass__ = ABCMeta @abstractmethod def method1(self): pass Test it (in ipython, python shell would be similar): In [2]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods method1 Notice the end of the last line, where the TypeError exception tells us that method1 has not been implemented ("abstract methods method1"). That was the method designated as @abstractmethod in the preceding code. Create a subclass that inherits Super, implement method1 in the subclass and you're done. My problem, which caused me to ask the original question, was how to specify an ABC that itself defines a list interface. My naive solution was to make an ABC as above, and in the inheritance parentheses say (list). My assumption was that the class would still be abstract (can't instantiate it), and would be a list. That was wrong; inheriting from list made the class concrete, despite the abstract bits in the class definition. Alex suggested inheriting from collections.MutableSequence, which is abstract (and so doesn't make the class concrete) and list-like. I used collections.Sequence, which is also abstract but has a shorter interface and so was quicker to implement. First, Super derived from Sequence, with nothing extra: from abc import abstractmethod from collections import Sequence class Super(Sequence): pass Test it: In [6]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods __getitem__, __len__ We can't instantiate it. A list-like full-citizen ABC; yea! Again, notice in the last line that TypeError tells us why we can't instantiate it: __getitem__ and __len__ are abstract methods. They come from collections.Sequence. But, I want a bunch of subclasses that all act like immutable lists (which collections.Sequence essentially is), and that have their own implementations of my added interface methods. In particular, I don't want to implement my own list code, Python already did that for me. So first, let's implement the missing Sequence methods, in terms of Python's list type, so that all subclasses act as lists (Sequences). First let's see the signatures of the missing abstract methods: In [12]: help(Sequence.__getitem__) Help on method __getitem__ in module _abcoll: __getitem__(self, index) unbound _abcoll.Sequence method (END) In [14]: help(Sequence.__len__) Help on method __len__ in module _abcoll: __len__(self) unbound _abcoll.Sequence method (END) __getitem__ takes an index, and __len__ takes nothing. And the implementation (so far) is: from abc import abstractmethod from collections import Sequence class Super(Sequence): # Gives us a list member for ABC methods to use. def __init__(self): self._list = [] # Abstract method in Sequence, implemented in terms of list. def __getitem__(self, index): return self._list.__getitem__(index) # Abstract method in Sequence, implemented in terms of list. def __len__(self): return self._list.__len__() # Not required. Makes printing behave like a list. def __repr__(self): return self._list.__repr__() Test it: In [34]: a = Super() In [35]: a Out[35]: [] In [36]: print a [] In [37]: len(a) Out[37]: 0 In [38]: a[0] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() /home/aaron/projects/test/test.py in __getitem__(self, index) 10 # Abstract method in Sequence, implemented in terms of list. 11 def __getitem__(self, index): ---> 12 return self._list.__getitem__(index) 13 14 # Abstract method in Sequence, implemented in terms of list. IndexError: list index out of range Just like a list. It's not abstract (for the moment) because we implemented both of Sequence's abstract methods. Now I want to add my bit of interface, which will be abstract in Super and therefore required to implement in any subclasses. And we'll cut to the chase and add subclasses that inherit from our ABC Super. from abc import abstractmethod from collections import Sequence class Super(Sequence): # Gives us a list member for ABC methods to use. def __init__(self): self._list = [] # Abstract method in Sequence, implemented in terms of list. def __getitem__(self, index): return self._list.__getitem__(index) # Abstract method in Sequence, implemented in terms of list. def __len__(self): return self._list.__len__() # Not required. Makes printing behave like a list. def __repr__(self): return self._list.__repr__() @abstractmethod def method1(): pass class Sub0(Super): pass class Sub1(Super): def __init__(self): self._list = [1, 2, 3] def method1(self): return [x**2 for x in self._list] def method2(self): return [x/2.0 for x in self._list] class Sub2(Super): def __init__(self): self._list = [10, 20, 30, 40] def method1(self): return [x+2 for x in self._list] We've added a new abstract method to Super, method1. This makes Super abstract again. A new class Sub0 which inherits from Super but does not implement method1, so it's also an ABC. Two new classes Sub1 and Sub2, which both inherit from Super. They both implement method1 from Super, so they're not abstract. Both implementations of method1 are different. Sub1 and Sub2 also both initialize themselves differently; in real life they might initialize themselves wildly differently. So you have two subclasses which both "is a" Super (they both implement Super's required interface) although their implementations are different. Also remember that Super, although an ABC, provides four non-abstract methods. So Super provides two things to subclasses: an implementation of collections.Sequence, and an additional abstract interface (the one abstract method) that subclasses must implement. Also, class Sub1 implements an additional method, method2, which is not part of Super's interface. Sub1 "is a" Super, but it also has additional capabilities. Test it: In [52]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods method1 In [53]: a = Sub0() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Sub0 with abstract methods method1 In [54]: a = Sub1() In [55]: a Out[55]: [1, 2, 3] In [56]: b = Sub2() In [57]: b Out[57]: [10, 20, 30, 40] In [58]: print a, b [1, 2, 3] [10, 20, 30, 40] In [59]: a, b Out[59]: ([1, 2, 3], [10, 20, 30, 40]) In [60]: a.method1() Out[60]: [1, 4, 9] In [61]: b.method1() Out[61]: [12, 22, 32, 42] In [62]: a.method2() Out[62]: [0.5, 1.0, 1.5] [63]: a[:2] Out[63]: [1, 2] In [64]: a[0] = 5 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: 'Sub1' object does not support item assignment Super and Sub0 are abstract and can't be instantiated (lines 52 and 53). Sub1 and Sub2 are concrete and have an immutable Sequence interface (54 through 59). Sub1 and Sub2 are instantiated differently, and their method1 implementations are different (60, 61). Sub1 includes an additional method2, beyond what's required by Super (62). Any concrete Super acts like a list/Sequence (63). A collections.Sequence is immutable (64). Finally, a wart: In [65]: a._list Out[65]: [1, 2, 3] In [66]: a._list = [] In [67]: a Out[67]: [] Super._list is spelled with a single underscore. Double underscore would have protected it from this last bit, but would have broken the implementation of methods in subclasses. Not sure why; I think because double underscore is private, and private means private. So ultimately this whole scheme relies on a gentleman's agreement not to reach in and muck with Super._list directly, as in line 65 above. Would love to know if there's a safer way to do that.

    Read the article

  • UiElement from abstract class

    - by plotnick
    I placed a control into a grid. let's say the control is derived from public class 'ButBase' which is derived in its turn from System.Windows.Controls.Button. The code normally compiles and app works just fine. But there's something really annoying. When you try to switch to xaml-design tab it will say 'The document root element is not supported by the visual designer', which is normal and I'm totally okay with that, but the thing is, that all the xaml code is underlined and VS2010 says: 'Cannot create an instance of ButBase' although still normally compiles and able to run. I've tried the same code in VS2008, it said that needs to see a public parameterless constructor in the ButBase, and even after I put one it showed the same error. What do I miss here?

    Read the article

  • UiElement based on another class

    - by plotnick
    I placed a control into a grid. let's say the control is derived from public class 'ButBase' which is derived in its turn from System.Windows.Controls.Button. The code normally compiles and app works just fine. But there's something really annoying. When you try to switch to xaml-design tab it will say 'The document root element is not supported by the visual designer', which is normal and I'm totally okay with that, but the thing is, that all the xaml code is underlined and VS2010 says: 'Cannot create an instance of ButBase' although still normally compiles and able to run. I've tried the same code in VS2008, it said that needs to see a public parameterless constructor in the ButBase, and even after I put one it showed the same error. What do I miss here?

    Read the article

  • Foolishness Check: PHP Class finds Class file but not Class in the file.

    - by Daniel Bingham
    I'm at a loss here. I've defined an abstract superclass in one file and a subclass in another. I have required the super-classes file and the stack trace reports to find an include it. However, it then returns an error when it hits the 'extends' line: Fatal error: Class 'HTMLBuilder' not found in View/Markup/HTML/HTML4.01/HTML4_01Builder.php on line 7. I had this working with another class tree that uses factories a moment ago. I just added the builder layer in between the factories and the consumer. The factory layer looked almost exactly the same in terms of includes and dependencies. So that makes me think I must have done something silly that's causes the HTMLBuilder.php file to not be included correctly or interpreted correctly or some such. Here's the full stack trace (paths slightly altered): # Time Memory Function Location 1 0.0001 53904 {main}( ) ../index.php:0 2 0.0002 67600 require_once( 'View/Page.php' ) ../index.php:3 3 0.0003 75444 require_once( 'View/Sections/SectionFactory.php' ) ../Page.php:4 4 0.0003 81152 require_once( 'View/Sections/HTML/HTMLSectionFactory.php' ) ../SectionFactory.php:3 5 0.0004 92108 require_once( 'View/Sections/HTML/HTMLTitlebarSection.php' ) ../HTMLSectionFactory.php:5 6 0.0005 99716 require_once( 'View/Markup/HTML/HTMLBuilder.php' ) ../HTMLTitlebarSection.php:3 7 0.0005 103580 require_once( 'View/Markup/MarkupBuilder.php' ) ../HTMLBuilder.php:3 8 0.0006 124120 require_once( 'View/Markup/HTML/HTML4.01/HTML4_01Builder.php' ) ../MarkupBuilder.php:3 Here's the code in question: Parent class (View/Markup/HTML/HTMLBuilder.php): <?php require_once('View/Markup/MarkupBuilder.php'); abstract class HTMLBuilder extends MarkupBuilder { public abstract function getLink($text, $href); public abstract function getImage($src, $alt); public abstract function getDivision($id, array $classes=NULL, array $children=NULL); public abstract function getParagraph($text, array $classes=NULL, $id=NULL); } ?> Child Class, (View/Markup/HTML/HTML4.01/HTML4_01Builder.php): <?php require_once('HTML4_01Factory.php'); require_once('View/Markup/HTML/HTMLBuilder.php'); class HTML4_01Builder extends HTMLBuilder { private $factory; public function __construct() { $this->factory = new HTML4_01Factory(); } public function getLink($href, $text) { $link = $this->factory->getA(); $link->addAttribute('href', $href); $link->addChild($this->factory->getText($text)); return $link; } public function getImage($src, $alt) { $image = $this->factory->getImg(); $image->addAttribute('src', $src); $image->addAttribute('alt', $alt); return $image; } public function getDivision($id, array $classes=NULL, array $children=NULL) { $div = $this->factory->getDiv(); $div->setID($id); if(!empty($classes)) { $div->addClasses($classes); } if(!empty($children)) { $div->addChildren($children); } return $div; } public function getParagraph($text, array $classes=NULL, $id=NULL) { $p = $this->factory->getP(); $p->addChild($this->factory->getText($text)); if(!empty($classes)) { $p->addClasses($classes); } if(!empty($id)) { $p->setID($id); } return $p; } } ?> I would appreciate any and all ideas. I'm at a complete loss here as to what is going wrong. I'm sure it's something stupid I just can't see...

    Read the article

  • Prefer class members or passing arguments between internal methods?

    - by geoffjentry
    Suppose within the private portion of a class there is a value which is utilized by multiple private methods. Do people prefer having this defined as a member variable for the class or passing it as an argument to each of the methods - and why? On one hand I could see an argument to be made that reducing state (ie member variables) in a class is generally a good thing, although if the same value is being repeatedly used throughout a class' methods it seems like that would be an ideal candidate for representation as state for the class to make the code visibly cleaner if nothing else. Edit: To clarify some of the comments/questions that were raised, I'm not talking about constants and this isn't relating to any particular case rather just a hypothetical that I was talking to some other people about. Ignoring the OOP angle for a moment, the particular use case that I had in mind was the following (assume pass by reference just to make the pseudocode cleaner) int x doSomething(x) doAnotherThing(x) doYetAnotherThing(x) doSomethingElse(x) So what I mean is that there's some variable that is common between multiple functions - in the case I had in mind it was due to chaining of smaller functions. In an OOP system, if these were all methods of a class (say due to refactoring via extracting methods from a large method), that variable could be passed around them all or it could be a class member.

    Read the article

  • ctags doesn't work when class is defined like "class Gem::SystemExitException"

    - by dan
    You can define a class in a namespace like this class Gem class SystemExitException end end or class Gem::SystemExitException end When code uses first method of class definition, ctags indexes the class definition like this: SystemExitException test_class.rb /^ class SystemExitException$/;" c class:Gem With the second way, ctags indexes it like this: Gem rubygems/exceptions.rb /^class Gem::SystemExitException < SystemExit$/;" c The problem with the second way is that you can't put your cursor (in vim) over a reference to "Gem::SystemExitException" and have that jump straight to the class definition. Your only recourse is to page through all the (110!) class definitions that start with "Gem::" and find the one you're looking for. Does anyone know of a workaround? Maybe I should report this to the maintainer of ctags?

    Read the article

  • C# How can I return my base class in a webservice

    - by HenriM
    I have a class Car and a derived SportsCar: Car Something like this: public class Car { public int TopSpeed{ get; set; } } public class SportsCar : Car { public string GirlFriend { get; set; } } I have a webservice with methods returning Cars i.e: [WebMethod] public Car GetCar() { return new Car() { TopSpeed = 100 }; } It returns: <Car> <TopSpeed>100</TopSpeed> </Car> I have another method that also returns cars like this: [WebMethod] public Car GetMyCar() { Car mycar = new SportsCar() { GirlFriend = "JLo", TopSpeed = 300 }; return mycar; } It compiles fine and everything, but when invoking it I get: System.InvalidOperationException: There was an error generating the XML document. --- System.InvalidOperationException: The type wsBaseDerived.SportsCar was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. I find it strange that it can't serialize this as a straight car, as mycar is a car. Adding XmlInclude on the WebMethod of ourse removes the error: [WebMethod] [XmlInclude(typeof(SportsCar))] public Car GetMyCar() { Car mycar = new SportsCar() { GirlFriend = "JLo", TopSpeed = 300 }; return mycar; } and it now returns: <Car xsi:type="SportsCar"> <TopSpeed>300</TopSpeed> <GirlFriend>JLo</GirlFriend> </Car> But I really want the base class returned, without the extra properties etc from the derived class. Is that at all possible without creating mappers etc? Please say yes ;)

    Read the article

  • How does versioning work when using Boost Serialization for Derived Classes?

    - by Venkata Adusumilli
    When a Client serializes the following data: InternationalStudent student; student.id("Client ID"); student.firstName("Client First Name"); student.country("Client Country"); the Server receives the following: ID = "Client ID" Country = "Client First Name" instead of the following: ID = "Client ID" Country = "Client Country" The only difference between the Server and Client classes is the First Name of the Student. How can we make the Server ignore First Name recieved from the Client and process the Country? Server Side Classes class Student { public: Student(){} virtual ~Student(){} public: std::string id() { return idM; } void id(std::string id) { idM = id; } protected: friend class boost::serialization::access; protected: std::string idM; protected: template<class A> void serialize(A& archive, const unsigned int /*version*/) { archive & BOOST_SERIALIZATION_NVP(idM); } }; class InternationalStudent : public Student { public: InternationalStudent() {} ~InternationalStudent() {} public: std::string country() { return countryM; } void country(std::string country) { countryM = country; } protected: friend class boost::serialization::access; protected: std::string countryM; protected: template<class A> void serialize(A& archive, const unsigned int /*version*/) { archive & BOOST_SERIALIZATION_NVP(boost::serialization::base_object<Student>(*this)); archive & BOOST_SERIALIZATION_NVP(countryM); } }; Client Side Classes class Student { public: Student(){} virtual ~Student(){} public: std::string id() { return idM; } void id(std::string id) { idM = id; } std::string firstName() { return firstNameM; } void firstName(std::string name) { firstNameM = name; } protected: friend class boost::serialization::access; protected: std::string idM; std::string firstNameM; protected: template<class A> void serialize(A& archive, const unsigned int /*version*/) { archive & BOOST_SERIALIZATION_NVP(idM); if (version >=1) { archive & BOOST_SERIALIZATION_NVP(firstNameM); } } }; BOOST_CLASS_VERSION(Student, 1) class InternationalStudent : public Student { public: InternationalStudent() {} ~InternationalStudent() {} public: std::string country() { return countryM; } void country(std::string country) { countryM = country; } protected: friend class boost::serialization::access; protected: std::string countryM; protected: template<class A> void serialize(A& archive, const unsigned int /*version*/) { archive & BOOST_SERIALIZATION_NVP(boost::serialization::base_object<Student>(*this)); archive & BOOST_SERIALIZATION_NVP(countryM); } };

    Read the article

  • Class Plugins in PHP?

    - by YuriKolovsky
    i just got some more questions while learning PHP, does php implement any built in plugin system? so the plugin would be able to change the behavior of the core component. for example something like this works: include 'core.class.php'; include 'plugin1.class.php'; include 'plugin2.class.php'; new plugin2; where core.class.php contains class core { public function coremethod1(){ echo 'coremethod1'; } public function coremethod2(){ echo 'coremethod2'; } } plugin1.class.php contains class plugin1 extends core { public function coremethod1(){ echo 'plugin1method1'; } } plugin2.class.php contains class plugin2 extends plugin1 { public function coremethod2(){ echo 'plugin2method2'; } } This would be ideal, if not for the problem that now the plugins are dependable on each other, and removing one of the plugins: include 'core.class.php'; //include 'plugin1.class.php'; include 'plugin2.class.php'; new plugin2; breaks the whole thing... are there any proper methods to doing this? if there are not, them i might consider moving to a different langauge that supports this... thanks for any help.

    Read the article

  • Interface vs Abstract Class (general OO)

    - by Kave
    Hi, I have had recently two telephone interviews where I've been asked about the differences between an Interface and an Abstract class. I have explained every aspect of them I could think of, but it seems they are waiting for me to mention something specific, and I dont know what it is. From my experience I think the following is true, if i am missing a major point please let me know: Interface: Every single Method declared in an Interface will have to be implemented in the subclass. Only Events, Delegates, Properties (C#) and Methods can exist in a Interface. A class can implement multiple Interfaces. Abstract Class Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#. 1) After all that the interviewer came up with the question What if you had an Abstract class with only abstract methods, how would that be different from an interface? I didnt know the answer but I think its the inheritance as mentioned above right? 2) An another interviewer asked me what if you had a Public variable inside the interface, how would that be different than in Abstract Class? I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either. Many Thanks for clarification, Kave See Also: When to use an interface instead of an abstract class and vice versa Interfaces vs. Abstract Classes How do you decide between using an Abstract Class and an Interface?

    Read the article

  • PHP Access property of a class from within a class instantiated in the original class.

    - by Iain
    I'm not certain how to explain this with the correct terms so maybe an example is the best method... $master = new MasterClass(); $master->doStuff(); class MasterClass { var $a; var $b; var $c; var $eventProccer; function MasterClass() { $this->a = 1; $this->eventProccer = new EventProcess(); } function printCurrent() { echo '<br>'.$this->a.'<br>'; } function doStuff() { $this->printCurrent(); $this->eventProccer->DoSomething(); $this->printCurrent(); } } class EventProcess { function EventProcess() {} function DoSomething() { // trying to access and change the parent class' a,b,c properties } } My problem is i'm not certain how to access the properties of the MasterClass from within the EventProcess-DoSomething() method? I would need to access, perform operations on and update the properties. The a,b,c properties will be quite large arrays and the DoSomething() method would be called many times during the execuction of the script. Any help or pointers would be much appreciated :)

    Read the article

  • DataAnnotation attributes buddy class strangeness - ASP.NET MVC

    - by JK
    Given this POCO class that was automatically generated by an EntityFramework T4 template (has not and can not be manually edited in any way): public partial class Customer { [Required] [StringLength(20, ErrorMessage = "Customer Number - Please enter no more than 20 characters.")] [DisplayName("Customer Number")] public virtual string CustomerNumber { get;set; } [Required] [StringLength(10, ErrorMessage = "ACNumber - Please enter no more than 10 characters.")] [DisplayName("ACNumber")] public virtual string ACNumber{ get;set; } } Note that "ACNumber" is a badly named database field, so the autogenerator is unable to generate the correct display name and error message which should be "Account Number". So we manually create this buddy class to add custom attributes that could not be automatically generated: [MetadataType(typeof(CustomerAnnotations))] public partial class Customer { } public class CustomerAnnotations { [NumberCode] // This line does not work public virtual string CustomerNumber { get;set; } [StringLength(10, ErrorMessage = "Account Number - Please enter no more than 10 characters.")] [DisplayName("Account Number")] public virtual string ACNumber { get;set; } } Where [NumberCode] is a simple regex based attribute that allows only digits and hyphens: [AttributeUsage(AttributeTargets.Property)] public class NumberCodeAttribute: RegularExpressionAttribute { private const string REGX = @"^[0-9-]+$"; public NumberCodeAttribute() : base(REGX) { } } NOW, when I load the page, the DisplayName attribute works correctly - it shows the display name from the buddy class not the generated class. The StringLength attribute does not work correctly - it shows the error message from the generated class ("ACNumber" instead of "Account Number"). BUT the [NumberCode] attribute in the buddy class does not even get applied to the AccountNumber property: foreach (ValidationAttribute attrib in prop.Attributes.OfType<ValidationAttribute>()) { // This collection correctly contains all the [Required], [StringLength] attributes // BUT does not contain the [NumberCode] attribute ApplyValidation(generator, attrib); } Why does the prop.Attributes.OfType<ValidationAttribute>() collection not contain the [NumberCode] attribute? NumberCode inherits RegularExpressionAttribute which inherits ValidationAttribute so it should be there. If I manually move the [NumberCode] attribute to the autogenerated class, then it is included in the prop.Attributes.OfType<ValidationAttribute>() collection. So what I don't understand is why this particular attribute does not work in when in the buddy class, when other attributes in the buddy class do work. And why this attribute works in the autogenerated class, but not in the buddy. Any ideas? Also why does DisplayName get overriden by the buddy, when StringLength does not?

    Read the article

  • Why and when should I make a class 'static'? What is the purpose of 'static' keyword on classes?

    - by Saeed Neamati
    The static keyword on a member in many languages mean that you shouldn't create an instance of that class to be able to have access to that member. However, I don't see any justification to make an entire class static. Why and when should I make a class static? What benefits do I get from making a class static? I mean, after declaring a static class, one should still declare all members which he/she wants to have access to without instantiation, as static too. This means that for example, Math class could be declared normal (not static), without affecting how developers code. In other words, making a class static or normal is kind of transparent to developers.

    Read the article

  • Java Design Questions - Class, Function, Access Modifiers

    - by Ron
    I am newbie to Java. I have some design questions. Say I have a crawler application, that does the following: 1. Crawls a url and gets its content 2. Parses the contents 3. Displays the contents How do you decide between implementing a function or a class? -- Should the parser be a function of the crawler class, or should it be a class in itself, so it can be used by other applications as well? -- If it should be a class, should it be protected or public class? How do you decide between implementing a public or protected class? -- If I had to create a class to generate stats from the parsed contents for eg, should that class be protected (so only the crawler class can access it) or should it be public? Thanks Ron

    Read the article

  • Is a base class with shared fields and functions good design

    - by eych
    I've got a BaseDataClass with shared fields and functions Protected Shared dbase as SqlDatabase Protected Shared dbCommand as DBCommand ... //also have a sync object used by the derived classes for Synclock'ing Protected Shared ReadOnly syncObj As Object = New Object() Protected Shared Sub Init() //initializes fields, sets connections Protected Shared Sub CleanAll() //closes connections, disposes, etc. I have several classes that derive from this base class. The derived classes have all Shared functions that can be called directly from the BLL with no instantiation. The functions in these derived classes call the base Init(), call their specific stored procs, call the base CleanAll() and then return the results. So if I have 5 derived classes with 10 functions each, totaling 50 possible function calls, since they are all Shared, the CLR only calls one at a time, right? All calls are queued to wait until each Shared function completes. Is there a better design with having Shared functions in your DAL and still have base class functions? Or since I have a base class, is it better to move towards instance methods within the DAL?

    Read the article

  • How can I load class's part using linq to sql without anonymous class or additional class?

    - by ais
    class Test { int Id{get;set;} string Name {get;set;} string Description {get;set;} } //1)ok context.Tests.Select(t => new {t.Id, t.Name}).ToList().Select(t => new Test{Id = t.Id, Name = t.Name}); //2)ok class TestPart{ int Id{get;set;} string Name {get;set;} } context.Tests.Select(t => new TestPart{Id = t.Id, Name = t.Name}).ToList().Select(t => new Test{Id = t.Id, Name = t.Name}); //3)error Explicit construction of entity type 'Test' in query is not allowed. context.Tests.Select(t => new Test{Id = t.Id, Name = t.Name}).ToList(); Is there any way to use third variant?

    Read the article

  • question about class derivation in c++?

    - by jack22
    hi, i want to know some things about class derivation in c++ so i have super class x and an inherited class y and i did this class x{ public:a; private:b; protected:c; } class y:public x{ public:d; } in this case how y can access a,b,and c and by how i mean(public,protected,private) the second case: class x{ public:a; private:b; protected:c; } class y:private x{ public:d; } the same question? the third case: class x{ public:a; private:b; protected:c; } class y:private x{ public:d; } again the same question? sorry i think i wrote too much bye

    Read the article

  • how can we call one class's method through another class's object in php

    - by hello
    I want to know that is there any method in PHP by which i can call one class's method from another class object. let me clear here is one class class A() { public function showData(){ //here is method of class A } } // here is another class class B(){ public function getData(){ //some method in class B } } //now i create two objects $objA= new class A(); $objB=new class B(); now i want to call this $objB->showData();<--- is that possible .. by any how method( using public, inheritence,child parent etc...) please help me

    Read the article

  • JQuery: loop through elements with more than one css class name that share only the first class name

    - by omaether
    Hello, I'm trying to use JQuery to loop through several div's with more than one class name, that all have the same first css class name and each one has a different second class name, e.g. <div class="maintext blue"> </div> <div class="maintext purple"> </div> <div class="maintext chartreuse"> </div> <div class="maintext puce"> </div> <div class="maintext lime"> </div> In JQuery I have tried $(".mainText").each(function (i) $(".mainText.*").each(function (i) $(".mainText" *).each(function (i) $(".mainText .*").each(function (i) But it will not select any of the divs with class="mainText ..." thanks for considering the question.

    Read the article

  • Give a reference to a python instance attribute at class definition

    - by Guenther Jehle
    I have a class with attributes which have a reference to another attribute of this class. See class Device, value1 and value2 holding a reference to interface: class Interface(object): def __init__(self): self.port=None class Value(object): def __init__(self, interface, name): self.interface=interface self.name=name def get(self): return "Getting Value \"%s\" with interface \"%s\""%(self.name, self.interface.port) class Device(object): interface=Interface() value1=Value(interface, name="value1") value2=Value(interface, name="value2") def __init__(self, port): self.interface.port=port if __name__=="__main__": d1=Device("Foo") print d1.value1.get() # >>> Getting Value "value1" with interface "Foo" d2=Device("Bar") print d2.value1.get() # >>> Getting Value "value1" with interface "Bar" print d1.value1.get() # >>> Getting Value "value1" with interface "Bar" The last print is wrong, cause d1 should have the interface "Foo". I know whats going wrong: The line interface=Interface() line is executed, when the class definition is parsed (once). So every Device class has the same instance of interface. I could change the Device class to: class Device(object): interface=Interface() value1=Value(interface, name="value1") value2=Value(interface, name="value2") def __init__(self, port): self.interface=Interface() self.interface.port=port So this is also not working: The values still have the reference to the original interface instance and the self.interface is just another instance... The output now is: >>> Getting Value "value1" with interface "None" >>> Getting Value "value1" with interface "None" >>> Getting Value "value1" with interface "None" So how could I solve this the pythonic way? I could setup a function in the Device class to look for attributes with type Value and reassign them the new interface. Isn't this a common problem with a typical solution for it? Thanks!

    Read the article

  • Which is the better C# class design for dealing with read+write versus readonly

    - by DanM
    I'm contemplating two different class designs for handling a situation where some repositories are read-only while others are read-write. (I don't foresee any need to a write-only repository.) Class Design 1 -- provide all functionality in a base class, then expose applicable functionality publicly in sub classes public abstract class RepositoryBase { protected virtual void SelectBase() { // implementation... } protected virtual void InsertBase() { // implementation... } protected virtual void UpdateBase() { // implementation... } protected virtual void DeleteBase() { // implementation... } } public class ReadOnlyRepository : RepositoryBase { public void Select() { SelectBase(); } } public class ReadWriteRepository : RepositoryBase { public void Select() { SelectBase(); } public void Insert() { InsertBase(); } public void Update() { UpdateBase(); } public void Delete() { DeleteBase(); } } Class Design 2 - read-write class inherits from read-only class public class ReadOnlyRepository { public void Select() { // implementation... } } public class ReadWriteRepository : ReadOnlyRepository { public void Insert() { // implementation... } public void Update() { // implementation... } public void Delete() { // implementation... } } Is one of these designs clearly stronger than the other? If so, which one and why? P.S. If this sounds like a homework question, it's not, but feel free to use it as one if you want :)

    Read the article

  • Request for advice about class design, inheritance/aggregation

    - by Lasse V. Karlsen
    I have started writing my own WebDAV server class in .NET, and the first class I'm starting with is a WebDAVListener class, modelled after how the HttpListener class works. Since I don't want to reimplement the core http protocol handling, I will use HttpListener for all its worth, and thus I have a question. What would the suggested way be to handle this: Implement all the methods and properties found inside HttpListener, just changing the class types where it matters (ie. the GetContext + EndGetContext methods would return a different class for WebDAV contexts), and storing and using a HttpListener object internally Construct WebDAVListener by passing it a HttpListener class to use? Create a wrapper for HttpListener with an interface, and constrct WebDAVListener by passing it an object implementing this interface? If going the route of passing a HttpListener (disguised or otherwise) to the WebDAVListener, would you expose the underlying listener object through a property, or would you expect the program that used the class to keep a reference to the underlying HttpListener? Also, in this case, would you expose some of the methods of HttpListener through the WebDAVListener, like Start and Stop, or would you again expect the program that used it to keep the HttpListener reference around for all those things? My initial reaction tells me that I want a combination. For one thing, I would like my WebDAVListener class to look like a complete implementation, hiding the fact that there is a HttpListener object beneath it. On the other hand, I would like to build unit-tests without actually spinning up a networked server, so some kind of mocking ability would be nice to have as well, which suggests I would like the interface-wrapper way. One way I could solve this would be this: public WebDAVListener() : WebDAVListener(new HttpListenerWrapper()) { } public WebDAVListener(IHttpListenerWrapper listener) { } And then I would implement all the methods of HttpListener (at least all those that makes sense) in my own class, by mostly just chaining the call to the underlying HttpListener object. What do you think? Final question: If I go the way of the interface, assuming the interface maps 1-to-1 onto the HttpListener class, and written just to add support for mocking, is such an interface called a wrapper or an adapter?

    Read the article

  • Statically Init a derived class

    - by AC
    With c++, Is there a way to get a derived class to inherit its own static initializer? I am trying to do something like the following: class Base { public: class StaticInit { public: virtual StaticInit() =0; }; }; class Derived: public Base { public: virtual StaticInit::StaticInit() { //do something with the derived class } static StaticInit init; } static Derived::StaticInit init; it would also be nice if I didn't have to define the init var in each derived class. I am currently redefining the StaticInit internal class in each derived class but it seems redundant. Each derived class is a singleton, and I need the instance to be stored in a lookup table at program startup.

    Read the article

  • base pointer to derived class

    - by Jay
    Suppose there are Base class and Derived class. Base *A = new Base; Here A is a pointer point to Base class, and new constructs one that A points to. I also saw Base *B = new Derived; How to explain this? B is a pointer to Base Class, and a Derived class constructed and pointed by B? If there is a function derived from Base class, say, Virtual void f(), and it's been overridden in Derived class, then B->f() will invoke which version of the function? version in Base class, or version that overridden in Derived Class. What if there is a new function void g()in Derived, is B->g() going to invoke this function properly? One more is, is int *a = new double; or int *a = new int; legal?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >